nabulke
nabulke

Reputation: 11275

Selecting an image on property change in viewmodel

I would like to implement a visual indication (light bulb) in my WPF application, that glows for a short time whenever a property (string RFID, raises PropertyChanged event) in my viewmodel (MVVM) changes. DataContext of my window is set to the viewmodel. I got two images showing a light bulb on/off.

I tried with triggers and styles, but it didn't work out:

    <Image>
        <Image.Style>
            <Style TargetType="Image">
                <Setter Property="Source" Value="LightGrey.png"/>
                <Style.Triggers>
                    <Trigger Property="RFID" Value="???">
                        <Setter Property="Source" Value="LightGreen.png"/>
                    </Trigger>
                </Style.Triggers>
            </Style>
        </Image.Style>
    </Image>

Any help is appreciated!

Upvotes: 1

Views: 267

Answers (2)

anivas
anivas

Reputation: 6547

If you dont want the additional bool property as suggested. You can write a simple value converter that does this.

    class AnyToBoolConverter: IValueConverter   
    { 
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
        { 
            return (value != null) ? true : false; 
        } 
          
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
        { 
            return DependencyProperty.UnsetValue; 
        } 
    } 

This converter will come in handy in many situations. And you can do this:                              

<DataTrigger Binding="{Binding Path=RFID, Converter={StaticResource boolConverter}}" Value="True"> 
      <Setter Property="Source" Value="LightGreen.png"/> 
</DataTrigger>

Upvotes: 1

Rachel
Rachel

Reputation: 132568

You could have a boolean IsLightOn property in your ViewModel, and your whenever RFID fires a PropertyChanged event, the ViewModel turns IsLightOn = true and sets a timer which turns IsLightOn = false after X seconds

Upvotes: 2

Related Questions