WPF MVVM:ICommand 绑定到控件
我完全迷失了 MVVM 中使用的命令绑定。我应该如何将我的对象绑定到窗口和/或其命令到控件以获取在 Button
Click
上调用的方法?
这是一个 CustomerViewModel
类:
public class CustomerViewModel : ViewModelBase
{
RelayCommand _saveCommand;
public ICommand SaveCommand
{
get
{
if (_saveCommand == null)
{
_saveCommand = new RelayCommand(param => this.Save(), param => this.CanSave);
NotifyPropertyChanged("SaveCommand");
}
return _saveCommand;
}
}
public void Save()
{
...
}
public bool CanSave { get { return true; } }
...
ViewModelBase
实现 INotifyPropertyChanged
接口 以下是将 Button
绑定到命令的方式:
<Button Content="Save" Margin="3" Command="{Binding DataContext.Save}" />
将 CustomerViewModel
的实例分配给包含 的窗口的
DataContext
按钮。
给定的示例不起作用:我已将断点放入 Save
方法中,但执行不会传递给该方法。我看过很多例子(也在 stackoverflow 上),但无法弄清楚应该如何指定绑定。
请告知,任何帮助将不胜感激。
谢谢。
PS 可能我需要在 Button 绑定中指定 RelativeSource
...类似这样:
Command="{Binding Path=DataContext.Save, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"
但是应该为祖先指定哪种类型?
I've totally lost in the command binding that is used in MVVM. How should I bind my object to the window and/or its command to the control to get method called on the Button
Click
?
Here is a CustomerViewModel
class:
public class CustomerViewModel : ViewModelBase
{
RelayCommand _saveCommand;
public ICommand SaveCommand
{
get
{
if (_saveCommand == null)
{
_saveCommand = new RelayCommand(param => this.Save(), param => this.CanSave);
NotifyPropertyChanged("SaveCommand");
}
return _saveCommand;
}
}
public void Save()
{
...
}
public bool CanSave { get { return true; } }
...
ViewModelBase
implements the INotifyPropertyChanged
interface
Here is how Button
is bound to the command:
<Button Content="Save" Margin="3" Command="{Binding DataContext.Save}" />
An instance of the CustomerViewModel
is assigned to the DataContext
of the window that contains a Button
.
The given example is not working: I've put break point into the Save
method but execution doesn't pass to the method. I've saw a lot of examples (on the stackoverflow too), but can't figure out how binding should be specified.
Please advise, any help will be appreciated.
Thanks.
P.S. Probably I need to specify RelativeSource
in the Button binding... something like this:
Command="{Binding Path=DataContext.Save, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"
but which type should be specified for ancestor?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您想要做的是直接绑定到 Save 方法。这不是怎么做。
假设您已将视图的 DataContext 设置为 CustomerViewModel 的实例,这就是绑定到 SaveCommand 的方式:
您不必调用
NotifyPropertyChanged("SaveCommand");
。What you are trying to do is to bind directly to the Save method. This is not how to do it.
Assuming that you have set the DataContext of your View to an instance of CustomerViewModel, this is how you bind to the SaveCommand:
You do not have to call
NotifyPropertyChanged("SaveCommand");
.