Rover
Rover

Reputation: 2240

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.

Upvotes: 6

Views: 7413

Answers (5)

Heinzi
Heinzi

Reputation: 172478

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?

Upvotes: 6

HCL
HCL

Reputation: 36815

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

Upvotes: 8

James Hay
James Hay

Reputation: 12720

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

Upvotes: 1

Dennis Traub
Dennis Traub

Reputation: 51694

Have a look at the Null Object Pattern

Upvotes: 1

Richard
Richard

Reputation: 30628

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.

Upvotes: 1

Related Questions