Change WPF Button Visibility Based On Command.CanExecute
Here's a quick way to change to the visibility of your WPF button based on its command status.
In the example below, there's a Button
that is bound to a property named Save
on view model. Save
is an ICommand
and the behavior of the button is to enable or disable itself based on whether or not the ICommand.CanExecute
returns true or false. This sets the button's IsEnabled
property, and thus we can set a binding on the button's Visibility
property that changes when the button is enabled or disabled. Note that in the binding, a BooleanToVisibilityConverter
is used to convert a boolean to a corresponding Visibility
enum value.
<Button
Command="{Binding Path=Save}"
Content="Save"
Visibility="{Binding RelativeSource={RelativeSource Mode=Self}, Path=IsEnabled, Converter={StaticResource BooleanToVisibilityConverter}}" />