2010-06-17 35 views
8

我有一个WPF Microsoft Surface应用程序,我使用的是MVVM模式。WPF:绑定到代码后面的命令

我有在代码中创建背后的一些按钮和我想的命令绑定到他们,但我只知道,在XAML

这样工作的:

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

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

那么,如何将一个命令绑定这样的代码在后面?

回答

15

假设你有一个名为您SurfaceButton为“SurfaceButton1”,你可以访问命令的情况下,你可以使用下面的代码:

SurfaceButton1.Command = SaveReservationCommand; 
+1

+1正确的答案。此外,如果需要,可以使用代码中的绑定(http://msdn.microsoft.com/en-us/magazine/cc700358.aspx#id0190003) – Anvaka 2010-06-17 08:32:26

+2

谢谢你的快速回答。没想到会这么简单;) – sofri 2010-06-17 09:10:03

+0

Binding可能会在后面的代码中被设置,但是实现不应该是这样,并且这个代码只有在它的时候才会起作用。 – David 2016-10-06 11:45:23

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

希望它可以帮助...如果事情不清楚,对不起,这是我的第一篇文章:)

12

接受的答案会是不错的按钮是否访问命令。但是,在MVVM中,这些通常是分开的(Button中的View和View中的Command)。在XAML中,您通常会使用数据绑定将其挂起(如问题中的示例)。

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

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