WPF IsEnabled Property (Button Example)Use the IsEnabled property with the Button control. Set IsEnabled in a C# event handler.
IsEnabled is a bool property. It is available on many controls in WPF, including the TextBox and Button. When IsEnabled is False, a control is made inactive—it cannot be clicked or used. We use it with an expression.
You will need to drag the controls around so that they are positioned in a nice way. The Grid control, which is nested by default in the Window, makes this much easier. Then we add code to the TextBox_TextChanged event handler.
And IsEnabled is assigned to the result of an expression. The expression evaluates to true when the TextBox has one or more characters.
So The Button becomes enabled when the TextBox has text. It remains disabled whenever the TextBox is empty.
Example markup, XAML:
Title="MainWindow" Height="350" Width="525">
<TextBox HorizontalAlignment="Left" Height="23" Margin="10,10,0,0"
<Button Content="Send" HorizontalAlignment="Left" Margin="135,10,0,0"
public partial class MainWindow : Window
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
// Cast TextBox.
TextBox box = sender as TextBox;
// If text is present, enable the button.
// ... Otherwise disable the button.
this.SendButton.IsEnabled = box.Text.Length > 0;
Expressions. Expressions can be used to make WPF programs better. Please notice how we use an expression to control the value of the IsEnabled property in the example. This means an if-statement is not required.
Instead The IsEnabled property is tied to an expression. It handles true and false values correctly.
And The enabled state of the Button will not lose sync with the TextBox. This approach leads to UIs that are reliable.
Summary. In WPF programs, many concepts are used together. For example, a TextChanged event on a TextBox affects the IsEnabled property of a Button. And a bool property can be set with a C# expression.