开发者

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开发者_JS百科 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.


Have a look at the Null Object Pattern


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜