65.9K
CodeProject is changing. Read more.
Home

How to make Button enabled/disabled depending on the TextBox Text property

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.70/5 (8 votes)

Jun 23, 2011

CPOL
viewsIcon

65944

Keep button inactive until a TextBox has a value, using WPF

Sometimes we need to enable/disable controls based on a property of another control. Like if a textbox has some value, only then enable the button, else disable.

In the example below, I have a textbox txtName and once the user enters something (as soon as) into the textbox, then enable the “Add Name” button.

<TextBox Name="txtName" Width="100" Height="30"></TextBox>

Way 1

<Button Content="Add Name " Width="100" Height="30" 
  IsEnabled="{Binding ElementName=txtName, Path=Text.Length, Mode=OneWay}"></Button>

Way 2

The same functionality can be achieved using triggers:

<Button Content="Add Name" Width="100" Height="30">
<Button.Style>
<Style>
  <Style.Triggers>
    <DataTrigger 
         Binding="{Binding ElementName=txtName,Path=Text.Length, Mode=OneWay}" 
         Value="0">
      <Setter Property="Button.IsEnabled" Value="False" />
    </DataTrigger>
  </Style.Triggers>
</Style>
</Button.Style>
</Button>

As soon as the user enters his name, the “Add Name” button is enabled.