简体   繁体   English

WPF:MVVM - 如果命令为null,则禁用按钮

[英]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. 在初始状态下,没有任何选定的对象,因此绑定不起作用,并且不会调用CanExecute How can i disable this button using MVVM? 如何使用MVVM禁用此按钮?

Solution: WPF/MVVM: Disable a Button's state when the ViewModel behind the UserControl is not yet Initialized? 解决方案: WPF / MVVM:当UserControl后面的ViewModel尚未初始化时,禁用Button的状态?

Guys, thanks for your answers and sorry for duplication of question. 伙计们,感谢您的回答,并对不起重复的问题。

Define a command that always return false to CanExecute. 定义始终向CanExecute返回false的命令。 Declare it at a global position such as in your App.Xaml. 在全局位置声明它,例如在App.Xaml中。 you can specify this empty-command then as the FallbackValue for all your command bindings you expect a null value first. 您可以将此empty-command指定为所有命令绑定的FallbackValue ,您希望首先使用null值。

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

You could create a trigger in XAML that disables the Button when the command equals x:Null . 您可以在XAML中创建一个触发器,当命令等于x:Null时禁用Button。

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? 在这个问题的答案中可以找到一个例子: WPF / MVVM:当UserControl后面的ViewModel尚未初始化时,禁用Button的状态?

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. 但是,另一种方法是使用基本ICommand初始化Command对象,其中CanExecute只返回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: 创建一个NullToBooleanConverter并将IsEnabled属性绑定到命令,通过转换器运行它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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