开发者

Selecting an image on property change in viewmodel

开发者 https://www.devze.com 2023-03-15 18:17 出处:网络
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) cha

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>开发者_StackOverflow社区;

Any help is appreciated!


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


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>
0

精彩评论

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

关注公众号