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

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

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

像这样:

 

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

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

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

 SurfaceButton1.Command = SaveReservationCommand; 

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

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

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

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

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