How can I apply a conditional effect to a button based on value in the ViewModel?

1.4k Views Asked by At

I can easily add a little glow effect to a button using something like this:

<Button ...>
  <Button.Effect>
    <DropShadowEffect ... />
  </Button.Effect>
</Button>

How can I apply the effect conditionally, based on a value in the ViewModel?

Basically I want the button to "glow" if a new document has been added in the last few days. I can supply the bool value indicating if the glow is required as a property of the ViewModel.

I was thinking of just creating two buttons attached to the same command, hiding one and showing the other based on the ViewModel. That would work, but it seems a bit brute forced.

Thoughts?

Thanks.

J

2

There are 2 best solutions below

2
M.E. On BEST ANSWER

You need to create a style for your Button with a DataTrigger like this:

<Button Content="Hello" Command="{Binding HelloCommand}">
    <Button.Style>
        <Style TargetType="Button">
            <Style.Triggers>
                <DataTrigger Binding="{Binding SomeCondition}" Value="True">
                    <Setter Property="Effect">
                        <Setter.Value>
                            <DropShadowEffect />
                        </Setter.Value>
                    </Setter>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>

Note that SomeCondition is a boolean property in your view model. Only when SomeCondition is true, the effect gets applied.

1
Abin On

I think you really need a DataTrigger Like Below,

<Style.Triggers>
    <DataTrigger Binding="{Binding PropertyFromViewModel}" Value="True">
      <Setter .../>
      <Setter .../>
   </DataTrigger>
</Style.Triggers>

Example

    <Button Content="Hello" Command={Binding YourCommand}>
        <Button.Style>
            <Style TargetType="{x:Type Button}">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Glow}" Value="True">
                        <Setter Property="Effect">
                            <Setter.Value>
                                <DropShadowEffect Color="Blue"/>
                            </Setter.Value>
                        </Setter>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Button.Style>
    </Button>