5

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.

Community
  • 1
  • 1
Rover
  • 2,203
  • 3
  • 24
  • 44
  • 1
    You could create a Style for the Button with a DataTrigger that disables the Button when {Binding Save} equals x:Null. – Heinzi Mar 03 '11 at 12:37
  • Thanks! I found the same solution: http://stackoverflow.com/questions/4423746/wpf-mvvm-disable-a-buttons-state-when-the-viewmodel-behind-the-usercontrol-is-n/4424241#4424241. But i can't mark your answer as accepted. – Rover Mar 03 '11 at 12:45
  • Thanks. I've added my comment as a "real answer" (and took the liberty of adding your link), so you can accept it now. :-) – Heinzi Mar 03 '11 at 16:55

5 Answers5

8

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}}" /> 
HCL
  • 36,053
  • 27
  • 163
  • 213
6

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?

Community
  • 1
  • 1
Heinzi
  • 167,459
  • 57
  • 363
  • 519
1

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.

Richard
  • 29,854
  • 11
  • 77
  • 120
1

Have a look at the Null Object Pattern

Dennis Traub
  • 50,557
  • 7
  • 93
  • 108
1

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}}" />
James Hay
  • 12,580
  • 8
  • 44
  • 67