简体   繁体   中英

WPF: MVVM - disable button if command is null

I have binding on some command:

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

Save is command of some object that can be selected from list. In initial state there is no any selected object so binding does not work and CanExecute does not invoked. How can i disable this button using MVVM?

Solution: WPF/MVVM: Disable a Button's state when the ViewModel behind the UserControl is not yet Initialized?

Guys, thanks for your answers and sorry for duplication of question.

Define a command that always return false to CanExecute. Declare it at a global position such as in your App.Xaml. you can specify this empty-command then as the FallbackValue for all your command bindings you expect a null value first.

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

You could create a trigger in XAML that disables the Button when the command equals x:Null .

An example can be found in the answer to this question: WPF/MVVM: Disable a Button`s state when the ViewModel behind the UserControl is not yet Initialized?

I'm not sure you'll be able to achieve this. However, an alternative would be to initialise the Command object initially with a basic ICommand where CanExecute simply returns False. You could then replace this when you're ready to put the real command in place.

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}}" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM