好的,XAML 非常简单,使用 MVVM 绑定到ICommand SomeCommand { get; }
视图模型上的属性:
<Button Command="{Binding Path=SomeCommand}">Something</Button>
If SomeCommand
回报null
,该按钮已启用。 (与CanExecute(object param)
方法上ICommand
,因为没有实例可以调用该方法)
现在的问题是:为什么该按钮启用?你会如何解决这个问题?
如果你按下“启用”按钮,显然什么也没有被调用。该按钮看起来已启用,这很丑陋。
我的同事找到了一个优雅的解决方案:使用绑定后备值!
public class NullCommand : ICommand
{
private static readonly Lazy<NullCommand> _instance = new Lazy<NullCommand>(() => new NullCommand());
private NullCommand()
{
}
public event EventHandler CanExecuteChanged;
public static ICommand Instance
{
get { return _instance.Value; }
}
public void Execute(object parameter)
{
throw new InvalidOperationException("NullCommand cannot be executed");
}
public bool CanExecute(object parameter)
{
return false;
}
}
然后 XAML 看起来像:
<Button Command="{Binding Path=SomeCommand, FallbackValue={x:Static local:NullCommand.Instance}}">Something</Button>
这个解决方案的优点是如果你打破了它会更好地工作得墨忒耳定律绑定路径中有一些点,其中每个实例可能会变成null
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)