Friday, September 21, 2012

Binding the IsEnabled property to whether a text block has data

Binding the IsEnabled property to whether a text block has data

I'm using silverlight for windows phone and I want to bind the IsEnabled property of a button to whether a textblock has text in it or not. In other words, I want my button to be enabled when the textblock's Text is not empty and disabled otherwise.

Is it possible to do this purely in XAML using Styles/Setters/Triggers or any other mechanism or do I have to write a converter?

PS: I'm still learning silverlight, .NET etc ..

Answers & Comments...

Answer: 1

As the types are not compatible (and you will generally want to avoid code-behind/dependency properties) a "string to enabled converter" is your best bet for this type of simple check.

As converters are shared around projects, and are only a minor entry in the XAML (and no changes to code-behind) you should not be worried about using converters... converters are your friends :)

Start making a library of useful converters as the same sorts of problems occur time and time again.

Here is some minimal code (no error checks) for a converter that does what you wanted:

using System; using System.Windows.Data;  namespace LengthToEnabledTest {     public class LengthToEnabledConverter : IValueConverter     {          #region IValueConverter Members          public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)         {             if (value is string)             {                 return (value as string).Length > 0;             }             throw new NotImplementedException();         }          public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)         {             throw new NotImplementedException();         }          

No comments:

Post a Comment

Send us your comment related to the topic mentioned on the blog