Wpf – Make Button enabled/disabled depending on the TextBox Text property in WPF

data-bindingwpfxaml

I was looking for code through google that enables and disables a button based on the text property from a textbox. If the textbox has some text then the button should be enabled or otherwise button should be disabled.

I got some code but code in xaml but no c#. I am not being able to understand how it works.

Please help me to understand the behaviour of the following code:

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

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

How is the IsEnabled button property working? How is true and false set to the IsEnabled property? What is Path? How does it work?

Best Answer

This article and article explain WPF data bindings and how paths work.

But the binding above will watch the Text property on the TextBox for changes. It will then watch the Length property on the value returned from the Text property, which is a string. The value of the Length property is passed to the IsEnbled property.

The value must also be converted, as you are assigning an Int32 (the Length property) to a Boolean (the IsEnabled property). This is generally done via type converters, which is why the above works (which surprises me).

UPDATE:

The first link above no longer works, as MSDN Magazine articles older than 2008 are no longer available online. They are available as CHM files though. The CHM link for the associated article, titled "Data Points: Data Binding in WPF", is:

http://download.microsoft.com/download/3/a/7/3a7fa450-1f33-41f7-9e6d-3aa95b5a6aea/MSDNMagazine2007_12en-us.chm

From MSDN:

2008 and older issues are only available as .chm files. On most versions of windows you must first save these files to your local machine, and then unblock the file in order to read it. To unblock a file, right click on it, and select properties, and then select the ‘unblock’ button. The content will then be available to read.