Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

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

0.00/5 (No votes)
24 Jun 2011 1  
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.


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

Way 1


ASP.NET
<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:


XML
<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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here