Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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="image1" false source="image2"

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

like image 512
Shimmy Weitzhandler Avatar asked Nov 03 '09 14:11

Shimmy Weitzhandler


2 Answers

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>
like image 128
Grokys Avatar answered Nov 16 '22 03:11

Grokys


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}}" />
like image 29
dnxit Avatar answered Nov 16 '22 02:11

dnxit