views:

183

answers:

1
+1  Q: 

Bind to not

Is there a super quick way to bind to the inverse of a boolean property? Something like this:

<TextBox Text="Some Text" IsEnabled="{Binding !EnableTextBox}" />

I know I can use a DataTrigger, but I was hoping for a nice shorthand.

+3  A: 

When I need to do this, I wrote a simple converter:

public class BoolInverterConverter : IValueConverter
{
 #region IValueConverter Members

 public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
 {
  if (value is bool)
  {
   return !(bool)value;
  }
  return value;
 }

 public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
 {
  throw new NotImplementedException();
 }

 #endregion
}

<TextBox Text="Some Text" IsEnabled="{Binding EnableTextBox, Converter={StaticResource BoolInverterConverter}}" />

Or a quicker solution would be just to add another read-only bool property to your VM and negate that value.

opedog
I thought of that but it doesn't end up being much shorted in the XAML then a DataTrigger. I was hoping for a super shorthand.
Jake Pearson
Yeah, converters can make your XAML rather ugly, and unless someone is already familiar with what it does they'll have to look it up, reducing code read time. If I have use one bool multiple places in my XAML where I need to enable some and disable others, I usually just go the read-only property route. If it's a one-off I use the converter.
opedog
Ewww, is it me or do all of these solutions available seem less than desirable. I'm in the same bind with the added complexity of needing to chain a BoolToVisibility converter with a BoolInverseConverter otherwise expose several Is and IsNot properties on my ViewModel. Both are not very pretty!
jpierson
UPDATE: I found a great solution here by leblancmeneses at the following MSDN Forum post. In the solution you put an OnTrue and an OnFalse property on the ValueConverter so you can configure it when it is declared, pretty slick.http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/f2154f63-ccb5-4d6d-8c01-81f9da9ab347/
jpierson