x:使用空字符串绑定图像

Sau*_*321 14 c# windows windows-10 windows-10-mobile uwp

在XAML中,我有以下行:

<Image x:Name="MainImage" 
       Source="{x:Bind ViewModel.MainPic,Mode=OneWay,TargetNullValue={x:Null}}"
       Stretch="UniformToFill"/>
Run Code Online (Sandbox Code Playgroud)

在ViewModel中:

public string MainPic
{
    get
    {
        if (Data == null)
            return default(string);
        else
            return Data.Photos.ElementAtOrDefault(0).url;
    }
}
Run Code Online (Sandbox Code Playgroud)

应用程序编译正常但在执行期间(因为数据在几秒钟后填充),应用程序崩溃时出现以下异常:

System.ArgumentException:参数不正确.

调试器中断:

            private void Update_ViewModel_MainPic(global::System.String obj, int phase)
            {
                if((phase & ((1 << 0) | NOT_PHASED | DATA_CHANGED)) != 0)
                {
 /*HERE>>*/          XamlBindingSetters.Set_Windows_UI_Xaml_Controls_Image_Source(this.obj23, (global::Windows.UI.Xaml.Media.ImageSource) global::Windows.UI.Xaml.Markup.XamlBindingHelper.ConvertValue(typeof(global::Windows.UI.Xaml.Media.ImageSource), obj), null);
                }
            }
Run Code Online (Sandbox Code Playgroud)

显然,这是因为MainPic返回null.

现在,这段代码在WP8.1中运行良好.我试过返回uri导致编译时间错误.我相信只有字符串可以绑定到Win 10中的图像源(?)我只想要一个空白区域,直到填充数据,因此我不希望将本地图像源作为后备.有人可以帮我为Win 10移植吗?


更新:

感谢回答的用户,得出以下结论(针对UWP):

  • 如果您将图像源绑定到a string,则它不能为null空或为空"".单个字符"x"或空格" "可以工作.
  • 如果绑定到a BitmapImage,则返回null作品.
  • 您可以使用@ Justin-xl提到的任何方法.对我来说,更改所有vm以停止返回null很难.因此,向xaml添加一个简单的转换器也可以解决问题.

这是转换器代码:

public object Convert(object value, Type targetType, object parameter, string language)
{
    if (string.IsNullOrEmpty(value as string))
    {
        return null;
    }
    else return new BitmapImage(new Uri(value as string, UriKind.Absolute));
}
Run Code Online (Sandbox Code Playgroud)

Jus*_* XL 14

如果你使用x:BindSourceImage需要绑定到完全相同的类型的属性ImageSource(如BitmapImage)代替string,否则会抛出一个编译时错误,而这正是一个编译时绑定是应该做的.旧绑定允许字符串 '因为它使用Reflection在运行时为您解析类型.

事实证明我的显式类型理论是错误的(感谢@igrali指出它).这Source确实需要一段string时间它不是null''.所以我们有两个选择来解决这个问题.

选项1

保持你uri的状态string,但是vm一旦检查你的,null或者''返回一些虚拟文本(甚至返回一封信x就行了!).

选项2

uri字符串更改为BitmapImage.然后您可以使用TargetNullValueFallbackValue处理空值和无效绑定.

... FallbackValue='http://Assets/SplashScreen.png' TargetNullValue='http://Assets/SplashScreen.png'}"
Run Code Online (Sandbox Code Playgroud)