Disable button in WPF?

I have Button and TextBox in my WPF application. How can I make the button not turned on until the user enters any text in the TextBox?

+41
button wpf textbox
May 25 '10 at 16:04
source share
5 answers

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> 
+41
May 25 '10 at 16:13
source share
β€” -

In MVVM (a lot of which is much simpler - you should try) you will have two properties in the ViewModel Text attached to your TextBox, and you will have the ICommand Apply property (or the like) associated with the button:

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

The ICommand interface has a CanExecute method in which you return true if (!string.IsNullOrWhiteSpace(this.Text) . The rest is done by WPF for you (enable / disable, execute the actual command when pressed).

A related article explains this in detail.

+14
May 25 '10 at 16:18
source share

By code:

 btn_edit.IsEnabled = true; 

In XAML:

 <Button Content="Edit data" Grid.Column="1" Name="btn_edit" Grid.Row="1" IsEnabled="False" /> 
+10
Mar 27 '14 at 8:25
source share

I know this is not as elegant as other posts, but this is a simpler xaml / codebehind example of how to do the same thing.

Xaml:

 <StackPanel Orientation="Horizontal"> <TextBox Name="TextBox01" VerticalAlignment="Top" HorizontalAlignment="Left" Width="70" /> <Button Name="Button01" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="10,0,0,0" /> </StackPanel> 

CodeBehind:

 Private Sub Window1_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded Button01.IsEnabled = False Button01.Content = "I am Disabled" End Sub Private Sub TextBox01_TextChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.TextChangedEventArgs) Handles TextBox01.TextChanged If TextBox01.Text.Trim.Length > 0 Then Button01.IsEnabled = True Button01.Content = "I am Enabled" Else Button01.IsEnabled = False Button01.Content = "I am Disabled" End If End Sub 
+5
May 25 '10 at 16:23
source share

You can subscribe to the TextChanged event on a TextBox , and if the text is empty, disable the Button . Or you can bind the Button.IsEnabled property to the Button.IsEnabled property and use a converter that returns true if there is otherwise text and false.

0
May 25 '10 at 16:12
source share



All Articles