Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Binding: !value [duplicate]

Tags:

I have button:

<Button Content="Stop loading" /> 

In ViewModel i have property IsLoaded. I don't want to write property IsNotLoaded but i want to use IsLoaded in binding and disable button when IsLoaded = true.

How implement something like this:

<Button Content="Stop loading" IsEnabled="{Binding !IsLoaded}" /> 

P.S. if it more difficult than writing of additional property, i will use IsNotLoaded property.

like image 843
Rover Avatar asked Jan 28 '11 16:01

Rover


2 Answers

The standard means of doing this is to make an IValueConverter that will invert your boolean values. While creating this class is more difficult than adding a new property, it's completely reusable - so later, you can reuse this in other bindings (without polluting your ViewModel with lots of !Property properties).

This class would look something like:

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

Then, you would add it to your resources:

<src:InvertBoolConverter x:Key="invertBoolConverter"/> 

Once you have this, you would use it like:

<Button Content="Stop loading"          IsEnabled="{Binding IsLoaded, Converter={StaticResource invertBoolConverter}}"  /> 
like image 96
Reed Copsey Avatar answered Nov 03 '22 06:11

Reed Copsey


While the converter answers are all valid, you may want to look at an alternative methodology: Commanding.

In WPF (and somewhat in Silverlight), you can bind an ICommand to that button. So, if you created, on your ViewModel, a property called CancelLoadingCommand that implemented ICommand, you'd bind the button as follows:

<Button Content="Stop Loading" Command="{Binding CancelLoadingCommand}" /> 

The implementation of the CancelLoadingCommand in your ViewModel would look something like:

    public ICommand CancelLoadingCommand     {         get         {             if (_cancelLoadingCommand== null)             {                 this._cancelLoadingCommand= new RelayCommand(                     delegate                     {                         // Cancel the loading process.                     },                     delegate                     {                         return !this.IsLoaded;                     }                 );             }              return _cancelLoadingCommand;         }     } 

Note, I'm using a RelayCommand here (which is part of the PRISM or MVVM-Light frameworks). I'd suggest looking into one of those as well.

I hope this helps.

like image 32
SergioL Avatar answered Nov 03 '22 08:11

SergioL