13

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

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

像这样:

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

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

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

4

4 回答 4

24

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

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

SurfaceButton.SetBinding (Button.CommandProperty, new Binding("SaveReservationCommand"));
于 2014-10-14T22:11:26.120 回答
21

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

SurfaceButton1.Command = SaveReservationCommand;
于 2010-06-17T08:14:55.000 回答
6

我从 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);

希望它有所帮助......如果有什么不清楚,对不起,这是我的第一篇文章:)

于 2012-09-12T09:32:16.200 回答
1

这有效

Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=UserControl, AncestorLevel=1}, Path=SaveReservationCommand}"
于 2019-05-14T10:30:03.357 回答