Bind Image.Source according to Boolean without a converter? Bind Image.Source according to Boolean without a converter? wpf wpf

Bind Image.Source according to Boolean without 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.