我有一个涉及大量代码的问题,但我已将其隔离。如果你想要一个 TL;DR; 再往下跳。如果您想要一些上下文,这是我的情况:
我为绑定创建了三个数据转换器。其中之一是“字符串前缀”:它为您输入的任何内容添加一个固定字符串的前缀。在当前示例中,该固定字符串是"ms-appx:///cache/"
. 第二个将string
type 转换为ImageSource
,第三个将多个转换器链接在一起。
然后我创建了一个名为LocalCacheFile
. 一切都如您所想。用于此的 Xaml 代码如下所示:
<Image Source="{x:Bind imageSource,Converter={StaticResource LocalCacheFile}}" />
但是,我遇到了以下问题。如果我尝试使用 FallbackValue 为imageSource
空时放置一个占位符图像,我只会得到奇怪的行为x:Bind
。
以下代码按预期工作:
<Image Source="{Binding imageSource,FallbackValue='ms-appx:///Assets/default.png',Converter={StaticResource LocalCacheFile}}" />
但
<Image Source="{x:Bind imageSource,FallbackValue='ms-appx:///Assets/default.png',Converter={StaticResource LocalCacheFile}}" />
才不是!
我已将其隔离为仅一个转换器,并且DependencyProperty.UnsetValue
x:Bind 似乎没有处理。
TL;博士; 这是我的字符串前缀的代码,如果我单独使用它作为测试会触发相同的错误行为:
public class StringPrefix : IValueConverter
{
public string prefix { get; set; }
public object Convert(object value, Type typeName, object parameter, string language)
{
if (value == DependencyProperty.UnsetValue || value == null || (string)value == "")
return DependencyProperty.UnsetValue ;
return (prefix + value.ToString());
}
public object ConvertBack(object value, Type typeName, object parameter, string language)
{
throw new NotImplementedException();
}
}
当使用Binding
. 与 .一起使用时会引发类型异常x:Bind
。
这是怎么回事?
编辑:有关异常的详细信息。
这是生成的代码:
private void Update_project_imageSource(global::System.String obj, int phase)
{
if((phase & ((1 << 0) | NOT_PHASED | DATA_CHANGED)) != 0)
{
XamlBindingSetters.Set_Windows_UI_Xaml_Controls_Image_Source(this.obj16, (global::Windows.UI.Xaml.Media.ImageSource)this.LookupConverter("LocalCacheFile").Convert(obj, typeof(global::Windows.UI.Xaml.Media.ImageSource), null, null), null);
}
}
异常详情:
System.InvalidCastException was unhandled by user code
HResult=-2147467262
Message=Unable to cast object of type 'System.__ComObject' to type 'Windows.UI.Xaml.Media.ImageSource'.
Source=Test
StackTrace:
at Test.Pages.ProjectView.ProjectView_obj1_Bindings.Update_project_imageSource(String obj, Int32 phase)
at Test.Pages.ProjectView.ProjectView_obj1_Bindings.Update_project(Project obj, Int32 phase)
at Test.Pages.ProjectView.ProjectView_obj1_Bindings.Update_(ProjectView obj, Int32 phase)
at Test.Pages.ProjectView.ProjectView_obj1_Bindings.Update()
at Test.Pages.ProjectView.<.ctor>b__6_0(FrameworkElement s, DataContextChangedEventArgs e)
InnerException:
(对我来说,看起来生成的代码只是不处理默认值的可能性。顺便说一句,那__ComObject
是DependencyProperty.UnsetValue
.
编辑 2:我应该补充一点,如果我将 Convert 函数更改为返回 null 而不是 DependencyProperty.UnsetValue,x:Bind
则函数,但是既不x:Bind
也不Binding
做他们预期的使用FallbackValue