[英]ImageBrush ImageSource x:Bind TargetNullValue different than datatamplate
因此,我有一個ListView
是x:Bind
到一個列表和一個DataTemplate
。
DataTemplate
具有一個用ImageBrush
填充的Elipse
。
一切正常,但:
如果列表中的項目的字符串URL圖像屬性的值為Null
,則應用程序崩潰。
我嘗試設置TargetNullValue
但是我的問題是模板的X:DataType
是API中的類,因此我無法控制它。 如果項目的圖像值為null,我想將圖像作為默認值。
換句話說,如果項目的圖像URL屬性為Null
,那么我希望XAML
從我的Assets
文件夾中加載預定義的圖像。
問題是,因為我已經將DataType
設置為該類,所以x:Bind
要執行的任何操作都必須在該類之內。
<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和x:Bind中的FallbackValue不同。
在Binding中,FallbackValue是當綁定無法返回值時要使用的值。
如果路徑根本不對數據源求值,或者使用雙向綁定在源上進行設置時,綁定使用FallbackValue會引發數據綁定引擎捕獲的異常。 如果源值是依賴項屬性哨兵值
DependencyProperty.UnsetValue
則還使用FallbackValue。
但是在x:Bind中,FallbackValue指定了無法解析源或路徑時要顯示的值。 它不能與DependencyProperty.UnsetValue一起使用。
對於您的方案,可以使用Converter來運行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>
占位符圖像效果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.