WPF Property Data binding to negate the property

data-bindingwpf

Is there any way to change the value of property at runtime in WPF data binding. Let's say my TextBox is bind to a IsAdmin property. Is there anyway I can change that property value in XAML to be !IsAdmin.

I just want to negate the property so Valueconverter might be an overkill!

NOTE: Without using ValueConverter

Best Answer

You can use an IValueConverter.

[ValueConversion(typeof(bool), typeof(bool))]
public class InvertBooleanConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        bool original = (bool)value;
        return !original;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        bool original = (bool)value;
        return !original;
    }
}

Then you'd setup your binding like:

<TextBlock Text="{Binding Path=IsAdmin, Converter={StaticResource boolConvert}}" />

Add a resource (usually in your UserControl/Window) like so:

<local:InvertBooleanConverter  x:Key="boolConvert"/>

Edit in response to comment:

If you want to avoid a value converter for some reason (although I feel that it's the most appropriate place), you can do the conversion directly in your ViewModel. Just add a property like:

public bool IsRegularUser
{
     get { return !this.IsAdmin; }
}

If you do this, however, make sure your IsAdmin property setter also raises a PropertyChanged event for "IsRegularUser" as well as "IsAdmin", so the UI updates accordingly.