c# - 绑定(bind)到 CheckBox 并以 MVVM 方式执行命令

标签 c# wpf mvvm binding

我有一个类似于 this one 的问题, 但在更详细的情况下。我也在尝试使用 Model View Viewmodel 模式实现解决方案。

MainView 中,我有一个按钮调用存储在 MainViewModel 中的命令(我们称之为 Execute)。我还希望在单击鼠标左键时调用此命令(实际上,仅在 Up 上),但仅在选中 MouseUpCheckBox 时调用。

当我在 View 中拥有所有代码时,我为 Execute 做了静态绑定(bind),但随后使用 ElementName 绑定(bind)到 Window (为 IsChecked 命名为 w_window) 并检查 MouseLeftButtonUpEvent 处理程序中的属性值。

XAML

<Button Command="{x:Static local:MainView.Execute}">
    Execute
</Button>
<CheckBox IsChecked="{Binding ElementName=w_window, Path=ExecuteOnMouseUp}">
    Execute on Mouse Up
</CheckBox>

C#

public MainView()
{
    InitializeComponent();
    this.CommandBindings.Add(new CommandBinding(Execute, ExecuteExecuted));
    MyDesigner.AddHandler(UIElement.MouseLeftButtonUpEvent, new RoutedEventHandler((o, eventArgs) =>
    {
        if (ExecuteOnMouseUp)
        {
            Execute.Execute(null, this);
        }
    }), true);
}

#region ExecuteOnMouseUp
/// <summary>
/// ExecuteOnMouseUp Dependency Property
/// </summary>
public static readonly DependencyProperty ExecuteOnMouseUpProperty =
    DependencyProperty.Register("ExecuteOnMouseUp", typeof(bool), typeof(MainView),
        new FrameworkPropertyMetadata((bool)false));

/// <summary>
/// Gets or sets the ExecuteOnMouseUp property. This dependency property 
/// indicates ....
/// </summary>
public bool ExecuteOnMouseUp
{
    get { return (bool)GetValue(ExecuteOnMouseUpProperty); }
    set { SetValue(ExecuteOnMouseUpProperty, value); }
}
#endregion

#region Execute
/// <summary>
/// The Execute command ....
/// </summary>
public static RoutedUICommand Execute
    = new RoutedUICommand("Execute", "Execute", typeof(MainView));

private void ExecuteExecuted(object sender, ExecutedRoutedEventArgs e)
{
    ...
}
#endregion

如何将此代码从我的 View 移植到 View 模型中?我应该使用附加属性吗?有没有办法将复选框值绑定(bind)到 CommandCanExecute 处理程序中的参数?处理这种情况的惯用 WPF/MVVM 方法是什么?

最佳答案

查看 this文章。它向您展示了如何构建一个 AttachedCommand 来完成您想要做的事情。

关于c# - 绑定(bind)到 CheckBox 并以 MVVM 方式执行命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3892882/

相关文章:

c# - 进行隧道事件的正确方法

c# - WPF 从任何绑定(bind)中取消绑定(bind)所有元素及其子元素

c# - 如何从字符中添加字符

c# - 中继命令上的 CanExecute 不起作用

c# - Entity Framework - 按 SQL 函数排序

c# - 异步无效、ASP.Net 和未完成操作的计数

c# - 如何让 suggester 组件在 SolrNet 中工作?

wpf - 追加 WPF 资源字符串

WPF ObservableCollection 编辑模式

wpf - 为什么在定义TreeView.ItemTemplate后TreeView不会自动为子节点选择DataTemplates?