开发者

Bind Image.Source according to Boolean without a converter?

I want to have an image bound to a boolean and have the source of the image to depend on the boolean value

i.e. true source="i开发者_如何学编程mage1" false source="image2"

I was wondering if there is a way to do it inline without need for a converter.


You can create a style on the Image which uses a DataTrigger to swap the image source depending on a binding. In this example the image changes depending on the value of a boolean called simply "Value".

    <Image Width="16">
        <Image.Style>
            <Style TargetType="{x:Type Image}">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Value}" Value="False">
                        <Setter Property="Source" Value="Resources/image1.png"/>
                    </DataTrigger>
                    <DataTrigger Binding="{Binding Value}" Value="True">
                        <Setter Property="Source" Value="Resources/image2.png"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Image.Style>
    </Image>


If anyone is looking for Value Converter for binding. Here is what I used

<Image Source="{Binding Converter={StaticResource ImageConverter},ConverterParameter=\{Status\}}" />

public class StatusToImageConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        string statusValue = parameter.ToString().ToUpper();

        if (!string.IsNullOrEmpty(statusValue))
        {
            string result = string.Empty;

            switch (statusValue)
            {
                case "IDLE":
                    result = "idle.png";
                    break;
                case "OFFLINE":
                    result = "offline.png";
                    break;
                default:
                    result = "online.png";
                    break;
            }

            var uri = new Uri("pack://application:,,,/PIE;component/Images/" + result);

            return uri;
        }

        return string.Empty;
    }

    // No need to implement converting back on a one-way binding
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return DependencyProperty.UnsetValue;
    }
}

Bounded Enum

public enum DevStatus 
{ 
   Idle = 1,
   Offline = 2, 
   Active = 3, 
}

Set Enum from ViewModel and converter will bind the appropriate image.

<Image Source="{Binding DevStatus, Converter={StaticResource ImageConverter}}" />


If you're just binding the Image::Source property directly then the only way to accomplish this is with a custom IValueConverter.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜