WPF:绑定到后面的代码中的命令

sof*_*fri 11 c# wpf command pixelsense

我有一个WPF Microsoft Surface应用程序,我正在使用MVVM-Pattern.

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

像这样:

<Custom:SurfaceButton Command="{Binding SaveReservationCommandBinding, Mode=OneWay}"/> 
Run Code Online (Sandbox Code Playgroud)

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

那么命令绑定如何在代码中起作用呢?

Nig*_*mes 20

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

当我的动态Button无法找到Command时,我的程序给了我一个错误(因为它在一个完全不同的命名空间中).这就是我最终解决这个问题的方法:

SurfaceButton.SetBinding (Button.CommandProperty, new Binding("SaveReservationCommand"));
Run Code Online (Sandbox Code Playgroud)


dec*_*one 19

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

SurfaceButton1.Command = SaveReservationCommand;
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你的快速回答.没想到会那么容易;) (2认同)

Zu1*_*779 5

我从 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);
Run Code Online (Sandbox Code Playgroud)

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