为什么启用按钮,如果命令绑定解析为空? [英] Why is a button enabled if the Command binding resolves to null?

查看:97
本文介绍了为什么启用按钮,如果命令绑定解析为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

OK,XAML非常简单,使用MVVM绑定到 ICommand SomeCommand {get; } 视图模型上的属性:

OK, the XAML is quite simple and uses MVVM to bind to an ICommand SomeCommand { get; } property on a view model:

<Button Command="{Binding Path=SomeCommand}">Something</Button>

如果 SomeCommand 返回 null ,则启用该按钮。 (与 ICommand 上的 CanExecute(object param)方法无关,因为没有实例调用该方法)

If SomeCommand returns null, the button is enabled. (Nothing to do with CanExecute(object param) method on ICommand, because there is no instance to call that method on)

现在的问题:为什么启用按钮?你将如何工作?

And now the question: Why is the button enabled? How would you work it around?

如果按下启用按钮,显然没有任何调用。

If you press the "enabled" button, obviously nothing is called. It is just ugly that the button looks enabled.

推荐答案

它被启用,因为这是默认状态。

It is enabled because that's the default state. Disabling it automatically would be an arbitrary measure that gives rise to other problems.

如果要禁用没有关联命令的按钮,请绑定 IsEnabled 属性为 SomeCommand 使用适当的转换器,例如:

If you want to have a button without an associated command be disabled, bind the IsEnabled property to SomeCommand using an appropriate converter, e.g.:

[ValueConversion(typeof(object), typeof(bool))]
public 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 NotSupportedException();
    }
}

这篇关于为什么启用按钮,如果命令绑定解析为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆