我在大多数表单上都有一个按钮条用户控件。
我添加了以下命令...
public ICommand Create
{
get
{
return buttonCreate.Command;
}
set
{
buttonCreate.Command = value;
}
}
我将它们设置为依赖项属性,以便可以绑定到它们...
public static readonly DependencyProperty CreateCommandProperty =
DependencyProperty.Register(
"Create",
typeof(ICommand),
typeof(StandardButtonStrip),
new PropertyMetadata((ICommand)null));
然后将我的用户控件绑定到命令...
<commoncontrols:StandardButtonStrip HorizontalAlignment="Stretch" Create="{Binding CreateCommand}" />
我正在如下设置命令...
_viewModel.CreateCommand = new DelegateCommand<object>(OnCreateCommand, CanCreate);
但是尽管我总是在我的CanCreate方法上返回true,但是该按钮被禁用了……如果我在return true上设置一个断点,它将永远不会触发!
public bool CanCreate(object parm)
{
return true;
}
我已经尝试过看看是否会刷新绑定,但是没有乐趣!
_viewModel.CreateCommand.RaiseCanExecuteChanged();
我认为问题在于用户控件以及如何将Command作为属性传递,但不确定...
这种外观,您在视图模型上具有依赖项属性。如果您真的在使用MVVM,那么绝对不是解决该问题的方法(不是因为对某种模式的虔诚奉献,而是因为它不是最佳方法)。
首先,您的视图模型是DependencyObject吗?
如果是,则应将其降级为实现INotifyPropertyChanged的类。为什么?因为Button的Command属性本身就是DependencyProperty(从ButtonBase继承),并且已经支持数据绑定。
如果不是,那么它的依赖项属性将不起作用,这很好,因为首先不应该在视图模型上具有依赖项属性。
您应该做的,就是将视图模型作为控件的DataContext(我猜您已经设置好了)。然后将视图模型的CreateCommand更改为普通的ICommand,并像这样(使用默认的StandardButtonStrip样式)绑定createButton的Command属性。
<Button Name="createButton" HorizontalAlignment="Stretch" Command="{Binding CreateCommand}" />
这样,它仍然可以重用,您只需要确保与用户控件关联的任何视图模型都具有ICommand类型的CreateCommand属性(默认情况下,该视图模型将继承到按钮控件-一个wpf成员想到的最美好的事情)。
所以回顾一下,您应该或多或少以相反的方式进行。
希望这很有帮助,欢呼。
对已接受答案的警告-
您是否覆盖了用户控件的任何功能?