我正在使用数据绑定作为Image
控件的源。
<Image Source="{Binding ImageUri}"/>
但是这个 ImageUri
可能为空,因此我想为它使用一个默认图像,一个占位符,例如可以在/Assets/PlaceHolder.png
中。
我该如何设置默认图像?谢谢。 (这是一个 WP8 应用程序,但不应与 WPF 不同)
我正在使用数据绑定作为Image
控件的源。
<Image Source="{Binding ImageUri}"/>
但是这个 ImageUri
可能为空,因此我想为它使用一个默认图像,一个占位符,例如可以在/Assets/PlaceHolder.png
中。
我该如何设置默认图像?谢谢。 (这是一个 WP8 应用程序,但不应与 WPF 不同)
您可以通过设置TargetNullValue
来实现。
<Image>
<Image.Source>
<Binding Path="ImageUri" >
<Binding.TargetNullValue>
<ImageSource>/Assets/PlaceHolder.png</ImageSource>
</Binding.TargetNullValue>
</Binding>
</Image.Source>
</Image>
在我的看法中,您可以采用更好的方式,即通过在Grid
布局中使用两个Image
控件,一个带有本地占位符源,另一个带有远程Binding
。当您的远程绑定为null时,本地图像已经存在。但是,如果绑定不为null,则一旦它被呈现,它会自动覆盖本地占位符图像。
<Grid>
<Image Source="Assets/Placeholder.png"/>
<Image Source="{Binding ImageUri}"/>
</Grid>
<Image Source="{Binding ImageUri}" ImageFailed="Image_ImageFailed"/>
使用以下C#代码来加载特定图像。
private void Image_ImageFailed(object sender, ExceptionRoutedEventArgs e)
{
((Image)sender).Source = new BitmapImage(new Uri("/Assets/MyDefaultImage.png", UriKind.Relative));
}
最初的回答:
<Image>
<Image.Source>
<Binding Path="ImageUri">
<Binding.TargetNullValue>
<BitmapImage UriSource="/ProjName;component/Assets/PlaceHolder.png" />
</Binding.TargetNullValue>
</Binding>
</Image.Source>
</Image>
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
<Image x:Name="GeologyMapsLegend" Stretch="Fill" Height="150">
<i:Interaction.Triggers>
<i:EventTrigger EventName="ImageFailed">
<ei:ChangePropertyAction PropertyName="Source" TargetName="GeologyMapsLegend">
<ei:ChangePropertyAction.Value>
<ImageSource>
/LanSysWebGIS;component/Pictures/Icon/NoImageAvailable.jpg
</ImageSource>
</ei:ChangePropertyAction.Value>
</ei:ChangePropertyAction>
</i:EventTrigger>
</i:Interaction.Triggers>
</Image>
使用TargetNullValue
属性。如果我不想显示任何图像,这非常有帮助。
/AssemblyName;component/Images/Placeholder.png
。 - Slate