ImageBrush ImageSource x:Bind TargetNullValue 与 datatamplate 不同

ImageBrush ImageSource x:Bind TargetNullValue different than datatamplate

所以,我有一个 ListViewx:Bind 到一个列表和一个 DataTemplate.

DataTemplate 有一个 Elipse 填充了一个 ImageBrush

一切正常,但是:

如果列表中的某个项目的字符串 URL 图像 属性 具有 Null 值,应用程序会崩溃。

我试过设置TargetNullValue,但我的问题是模板的X:DataType是API的class,所以我无法控制它。我想要一个图像作为默认值,以防该项目的图像值为 null。

换句话说,如果项目的图像 URL 属性 是 Null,我希望 XAML 从我的 Assets 文件夹加载预定义图像.

问题是,因为我已将 DataType 设置为 class,所以我 x:Bind 的任何内容都必须在 class.[=30= 内]

<Ellipse Width="40" Height="40">
    <Ellipse.Fill>
        <ImageBrush ImageSource="{x:Bind IconUrl, Mode=OneWay,TargetNullValue=/Assets/NoAvatarIcon.png}"/>
    </Ellipse.Fill>
</Ellipse>

以上示例不适用于 ImageSource 中的 Null 字符串,因为 Path 设置为 Class.

对吧?有什么解决方法吗?

Binding中的FallbackValue和x:Bind不一样

在绑定中,FallbackValue 是绑定无法return 值时使用的值。

A binding uses FallbackValue for cases where the Path doesn't evaluate on the data source at all, or if attempting to set it on the source with a two-way binding throws an exception that's caught by the data binding engine. FallbackValue is also used if the source value is the dependency property sentinel value DependencyProperty.UnsetValue.

但在 x:Bind 中,FallbackValue 指定了一个在无法解析源或路径时显示的值。它不能与 DependencyProperty.UnsetValue.

一起使用

对于您的场景,您可以使用转换器来操作DependencyProperty.UnsetValue,就像下面的代码一样。

public class ImageConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        object res;        
        res = (value == null ? false : true) ? string.IsNullOrEmpty(value.ToString()) ? null : new BitmapImage(new Uri(value.ToString())) : null;
        return res;
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        throw new NotImplementedException();
    }
}

Xaml 文件中的用法

  <Page.Resources>
        <local:ImageConverter x:Key="cm" />
    </Page.Resources>
    <StackPanel Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <ListView x:Name="MyListView" ItemsSource="{x:Bind Items}">
            <ListView.ItemTemplate>
                <DataTemplate x:DataType="local:HeadPhoto">
                    <Ellipse Width="40" Height="40">
                        <Ellipse.Fill>
                            <ImageBrush ImageSource="{x:Bind PicUri,TargetNullValue=/Assets/pic.png,Converter={StaticResource cm }}" />
                        </Ellipse.Fill>
                    </Ellipse>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </StackPanel>
</Page>

占位符图像效果。