Wpf 在MVVM中处理单击事件的最佳方法是什么?
在MVVM中处理单击事件的最佳方法是什么?有没有最好的办法 我找到了两种解决办法: 使用relaycommand:Wpf 在MVVM中处理单击事件的最佳方法是什么?,wpf,mvvm,relaycommand,attachedbehaviors,Wpf,Mvvm,Relaycommand,Attachedbehaviors,在MVVM中处理单击事件的最佳方法是什么?有没有最好的办法 我找到了两种解决办法: 使用relaycommand: RelayCommand buttonAddCategory_Click; public ICommand ButtonAddCategory_Click { get { return buttonAddCategory_Click ?? (buttonAddCategory_Click = new RelayCommand(param =>
RelayCommand buttonAddCategory_Click;
public ICommand ButtonAddCategory_Click
{
get
{
return buttonAddCategory_Click ?? (buttonAddCategory_Click = new RelayCommand(param => this.AddCategory(),
param => true));
}
}
赞成:?;相反:如果我要更改ui元素,需要解决事件问题
随附行为:
public static bool GetIsResetMouseLeftButtonDown(TreeView treeView)
{
return (bool)treeView.GetValue(IsResetMouseLeftButtonDownProperty);
}
public static void SetIsResetMouseLeftButtonDown(TreeView treeViewItem, bool value)
{
treeViewItem.SetValue(IsResetMouseLeftButtonDownProperty, value);
}
public static readonly DependencyProperty IsResetMouseLeftButtonDownProperty =
DependencyProperty.RegisterAttached("PreviewMouseLeftButtonDown", typeof(bool), typeof(TreeViewBehavior),
new UIPropertyMetadata(false, OnIsMouseLeftButtonDownChanged));
赞成:您已经为ui上的更改发送了ventarg;contra:访问其他控件
现在我使用两种解决方案。按钮中的RellayCommand(带有ui更新事件)和附加的treeview行为,以便在用户单击时取消选择treeview项。对我来说,这个问题没有简单的答案。 我就是这么看的:
- 如果您在VM上有一个已定义的状态更改,请公开一个RelayCommand,该命令可以绑定到触发它的某个对象。在99.9%的情况下,这是一个按钮/菜单项。一些容易使用的东西。剩下的案例->可能需要一些变通方法,比如从视图中调用方法。 因此,如果您真的以VM为目标,那么应该使用RelayCommand
- 另一方面,焦点更改是与视图相关的功能。我觉得这和WM无关。这意味着对我来说,它应该在视图中实现。所以对我来说,我甚至会选择一个直接的事件处理程序来完成这项工作
<Button Name="SaveBtnr" VerticalAlignment="Bottom"
Command="{Binding Save}" Click="OnSaveClick"
CommandParameter="{Binding}">Save</Button>
然后你的命令:
public void SaveCommand(object parameter)
{
//SaveStuff
}
public void SaveCommand(object parameter)
{
//SaveStuff
}