【发布时间】:2012-05-25 18:52:32
【问题描述】:
假设您有一个按钮,其command 属性绑定到某个集合的当前项的某个ICommand。
当集合为null 时,按钮保持启用状态,单击它似乎是无操作。我希望按钮保持禁用状态。我想出了以下方法,以便在集合为空时保持禁用按钮。然而,对于可以也许以更自然、更简单和更像 MVVM 的方式完成的事情来说,这似乎有点太复杂了。
因此问题是:有没有更简单的方法来禁用该按钮,最好是在不使用代码隐藏的情况下?
.xaml:
<Button Content="Do something" >
<Button.Command>
<PriorityBinding>
<Binding Path="Items/DoSomethingCmd" />
<Binding Path="DisabledCmd" />
</PriorityBinding>
</Button.Command>
</Button>
.cs:
public class ViewModel : NotificationObject
{
ObservableCollection<Foo> _items;
public DelegateCommand DisabledCmd { get; private set; }
public ObservableCollection<Foo> Items {
get { return _items; }
set { _items = value; RaisePropertyChanged("Items"); }
}
public ViewModel()
{
DisabledCmd = new DelegateCommand(DoNothing, CantDoAnything);
}
void DoNothing() { }
bool CantDoAnything()
{
return false;
}
}
编辑:
几点说明:
- 我知道我可以使用 lambda 表达式,但在这个示例代码中我没有。
- 我知道谓词是什么。
- 我看不出用
DoSomethingCmd.CanExecute做某事会有什么帮助,因为没有DoSomethingCmd可以访问而没有当前项目。 - 所以我将重新提出我的问题:如何避免使用
DisabledCmd?我对提升DoSomethingCmd不感兴趣,因为它不是我想要的。否则我不会问这个问题。
另一个修改:
所以我基本上采用了这个答案作为解决方案:WPF/MVVM: Disable a Button's state when the ViewModel behind the UserControl is not yet Initialized?
我相信,这正是 hbarck 的建议。
【问题讨论】: