Save - a command ...">

WPF: MVVM - disable the button if the command is zero

I have a binding to some command:

<Button Command="{Binding Save}" /> 

Save - a command of some object that can be selected from the list. In the initial state, there is no selected object, so the binding does not work and CanExecute is not called. How to disable this button using MVVM?

WPF / MVVM: disable button state when ViewModel behind UserControl is not initialized yet?

Guys, thanks for your answers and sorry for duplicating the question.

+4
source share
5 answers

You can create a trigger in XAML that disables the button when the command is x:Null .

In the answer to this question you can find an example: WPF / MVVM: disable the button state when the ViewModel behind UserControl is not yet initialized?

+5
source

Define a command that always returns false in CanExecute. Declare it in a global position, for example in your App.Xaml. you can specify this empty command, and then as a FallbackValue for all your command bindings you expect a null value first.

 <Button Command="{Binding Save,FallbackValue={StaticResource KeyOfYourEmptyCommand}}" /> 
+6
source

I'm not sure that you can achieve this. However, an alternative would be to initialize the Command object with the original base ICommand, where CanExecute simply returns False. You can then replace this when you are ready to apply the real command.

+1
source

Create a NullToBooleanConverter and bind the IsEnabled property to the command, running it through the converter:

 class NullToBooleanConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return value != null; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } 

Then

 <UserControl.Resources> <Extentions:NullToBooleanConverter x:Key="NullToBooleanConverter" /> </UserControl.Resources> <Button Content="Hello" IsEnabled="{Binding Save, Converter={StaticResource NullToBooleanConverter}}" /> 
+1
source

Source: https://habr.com/ru/post/1342115/


All Articles