如果绑定源为null,如何为Image设置默认源?

问题描述 投票:12回答:7

我正在使用绑定作为Image控件的来源。

<Image Source="{Binding ImageUri}"/>

但是这个ImageUri可以为null,因此我想使用默认图像,一个占位符,例如,可以在/Assets/PlaceHolder.png中。

如何设置默认图像?谢谢。 (这是一个WP8应用程序,但不应该与WPF不同)

wpf xaml windows-phone-7 windows-phone-8
7个回答
23
投票

你可以通过设置TargetNullValue来实现它

<Image>
    <Image.Source>
        <Binding Path="ImageUri" >
            <Binding.TargetNullValue>
                <ImageSource>/Assets/PlaceHolder.png</ImageSource>
            </Binding.TargetNullValue>
        </Binding>
    </Image.Source>
</Image>

3
投票

您可以在图像上设置ImageFailed事件,

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

3
投票

你可以实际上走另一条路,这是一个更好的经验,在我看来只需在Image布局中使用两个Grid控件,一个使用本地占位符源,另一个使用远程Binding。远程绑定为空时,本地映像已存在。但是,如果绑定不为null,则在呈现后它会自动覆盖本地占位符图像。

<Grid>
    <Image Source="Assets/Placeholder.png"/>
    <Image Source="{Binding ImageUri}"/>
</Grid>

1
投票

您可以使用ImageFailed事件和ChangePropertyAction。

此代码段为我工作:

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>

0
投票

使用TargetNullValue属性。如果我不想显示任何图像,这将非常有用。


0
投票

你可以试试这个:

<Image>
    <Image.Source>
        <Binding Path="ImageUri">
            <Binding.TargetNullValue>
                <BitmapImage UriSource="/ProjName;component/Assets/PlaceHolder.png" />                    
            </Binding.TargetNullValue>
        </Binding>
    </Image.Source>
</Image>

-1
投票

你应该尝试在这里玩FallBackValue。这两个链接应该提供更多帮助

WPF Binding - Default value for empty string

MSDN

© www.soinside.com 2019 - 2024. All rights reserved.