gpt4 book ai didi

c# - x :Bind image with null string

转载 作者:可可西里 更新时间:2023-11-01 12:27:39 30 4
gpt4 key购买 nike

在 XAML 中,我有以下行:

<Image x:Name="MainImage" 
Source="{x:Bind ViewModel.MainPic,Mode=OneWay,TargetNullValue={x:Null}}"
Stretch="UniformToFill"/>

在 View 模型中:

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

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

System.ArgumentException: The parameter is incorrect.

调试器中断于:

            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);
}
}

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

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


更新:

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

  • 如果您将图像源绑定(bind)到 string,则它不能为 null 或空 ""。单个字符 "x" 或空格 "" 都可以。
  • 如果您绑定(bind)到 BitmapImage,则返回 null 有效。
  • 您可以使用@Justin-xl 提到的任何方法。为了我,更改所有虚拟机以停止返回 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));
}

最佳答案

如果您使用x:BindImageSource 需要绑定(bind)到完全相同类型的属性ImageSource(例如BitmapImage)而不是string,否则会抛出编译时错误,这正是编译时绑定(bind)应该去做。旧绑定(bind)允许使用字符串,因为它使用反射 在运行时为您解析类型。

事实证明我的显式类型理论是错误的(感谢@igrali 指出)。 Source 确实采用 string,只要它不是 null''。因此,我们有两个选择来解决这个问题。

选项 1

将您的 uri 保留为 string,但检查您的 vm,一旦它为 null'',返回一些虚拟文本(即使返回字母 x 也行!)。

选项 2

uristring 更改为 BitmapImage。然后您可以使用 TargetNullValueFallbackValue 来处理空值和无效绑定(bind)。

... FallbackValue='http://Assets/SplashScreen.png' TargetNullValue='http://Assets/SplashScreen.png'}"

关于c# - x :Bind image with null string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31897154/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com