【问题标题】:WPF: Binding to commands in code behindWPF:绑定到代码中的命令
【发布时间】:2010-06-17 08:09:38
【问题描述】:

我有一个 WPF Microsoft Surface 应用程序,并且正在使用 MVVM 模式。

我有一些在后面的代码中创建的按钮,我想将命令绑定到它们,但我只知道它在 XAML 中是如何工作的

像这样:

<Custom:SurfaceButton Command="{Binding SaveReservationCommandBinding, Mode=OneWay}"/> 

但我不能这样做,因为我的按钮不存在于 XAML 中,只存在于后面的代码中。

那么像这样的命令绑定如何在代码后面工作呢?

【问题讨论】:

    标签: c# wpf command pixelsense


    【解决方案1】:

    如果按钮可以访问命令,则接受的答案将非常有用。但是,在 MVVM 中,这些通常是分开的(视图中的按钮和视图模型中的命令)。在 XAML 中,您通常会使用数据绑定来连接它(如问题中的示例)。

    当我的动态按钮找不到命令时(因为它位于完全不同的命名空间中),我的程序给了我一个错误。这就是我最终解决这个问题的方法:

    SurfaceButton.SetBinding (Button.CommandProperty, new Binding("SaveReservationCommand"));
    

    【讨论】:

    • item2.SetBinding(MenuItem.CommandProperty, new Binding("LogoutCommand", source: BindingContext));我不知道为什么,但我的情况只有在我明确定义来源时才有效
    【解决方案2】:

    假设您将 SurfaceButton 命名为“SurfaceButton1”并且您可以访问该命令的实例,您可以使用以下代码:

    SurfaceButton1.Command = SaveReservationCommand;
    

    【讨论】:

    • +1 表示正确答案。此外,如果需要,可以在代码中使用绑定 (msdn.microsoft.com/en-us/magazine/cc700358.aspx#id0190003)
    • 感谢您的快速回答。没想到会那么容易;)
    • 绑定可能在后面的代码中设置,但实现不应该是这样,并且只有在这样的情况下才能使用此代码。
    【解决方案3】:

    我从 Anvaka 发布的链接中获取代码作为模板。我使用 Telerik 的 RadMenuItem,但您当然可以使用任何其他公开 Command 属性的组件。

    item = new RadMenuItem();
    item.Header = "Hide Column";
    DependencyProperty commProp = RadMenuItem.CommandProperty;
    if (!BindingOperations.IsDataBound(item, commProp)) {
      Binding binding = new Binding("HideColumnCommand");
      BindingOperations.SetBinding(item, commProp, binding);
    }
    //this is optional, i found easier to pass the direct ref of the parameter instead of another binding (it would be a binding to ElementName).
    item.CommandParameter = headerlCell.Column;
    menu.Items.Add(item);
    

    希望对您有所帮助......如果有什么不清楚的地方,抱歉,这是我的第一篇文章 :)

    【讨论】:

      【解决方案4】:

      这行得通

      Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=UserControl, AncestorLevel=1}, Path=SaveReservationCommand}"
      

      【讨论】:

      • 你是对的。我不知道我为什么这样回答:)
      猜你喜欢
      • 2021-07-19
      • 1970-01-01
      • 2013-05-09
      • 2011-11-07
      • 1970-01-01
      • 2018-07-17
      • 2018-04-06
      • 2016-05-07
      • 2013-09-16
      相关资源
      最近更新 更多