wpfuser-interfacebuttoneffectsdropshadoweffect

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


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


Solution

  • 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.