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.
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}}" />
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With