Pablote February 2016

WPF MVVM dependency Property Get negative value

I have two buttons, SEND and UNSEND. I want to enable or disable the buttons using the boolean IsSended.

I've created a dependency property which can be used to enable one of the buttons, but how I can take the negative value to control the other button?

VIEW

dxb:BarButtonItem Content="SEND" IsEnabled="{Binding !IsSent}" 
dxb:BarButtonItem Content="UNSEND" IsEnabled="{Binding IsSent}" 

VIEWMODEL

public Boolean IsSent
{
   get { return (Boolean) GetValue(IsSendedProperty); }
   set { SetValue(IsSendedProperty, value); }
}

public static readonly DependencyProperty IsSendedProperty = DependencyProperty.Register("IsSent", typeof(Boolean), typeof(ViewModel), new PropertyMetadata(default(Boolean)));

Answers


Rhys February 2016

There are a number of was to do this in WPF; IValueConverters, DataTemplate or overriding the ControlTemplate.

It is hard to know which would be the best in the long run for your particular application, but the simplest to show here is the IValueConverter.

Add a class called, for example, NegateBoolConverter

public class NegateBoolConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return !(bool)value;
    }


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

Create an instance of this class in XAML (I put all my converters all the way up in the App.xaml, but you could put it in the <Window.Resources> section.

  <Window.Resources>
    <local:NegateBoolConverter x:Key="MyConverter"/>
  </Window.Resources>

where local: is a namespace to the converter class

Then your binding becomes:

  <dxb:BarButtonItem Content="SEND" IsEnabled="{Binding IsSended, Converter={StaticResource MyConverter}}">

Post Status

Asked in February 2016
Viewed 3,915 times
Voted 8
Answered 1 times

Search




Leave an answer