Disable button in WPF? Disable button in WPF? wpf wpf

Disable button in WPF?


This should do it:

<StackPanel>    <TextBox x:Name="TheTextBox" />    <Button Content="Click Me">        <Button.Style>            <Style TargetType="Button">                <Setter Property="IsEnabled" Value="True" />                <Style.Triggers>                    <DataTrigger Binding="{Binding Text, ElementName=TheTextBox}" Value="">                        <Setter Property="IsEnabled" Value="False" />                    </DataTrigger>                </Style.Triggers>            </Style>        </Button.Style>    </Button></StackPanel>


In MVVM (wich makes a lot of things a lot easier - you should try it) you would have two properties in your ViewModel Text that is bound to your TextBox and you would have an ICommand property Apply (or similar) that is bound to the button:

<Button Command="Apply">Apply</Button>

The ICommand interface has a Method CanExecute that is where you return true if (!string.IsNullOrWhiteSpace(this.Text). The rest is done by WPF for you (enabling/disabling, executing the actual command on click).

The linked article explains it in detail.


By code:

btn_edit.IsEnabled = true;

By XAML:

<Button Content="Edit data" Grid.Column="1" Name="btn_edit" Grid.Row="1" IsEnabled="False" />