[英]WPF: Binding to commands in code behind
我有一個WPF Microsoft Surface應用程序,我正在使用MVVM-Pattern。
我有一些在代碼后面創建的按鈕,我想將命令綁定到它們,但我只知道它在XAML中是如何工作的
像這樣:
<Custom:SurfaceButton Command="{Binding SaveReservationCommandBinding, Mode=OneWay}"/>
但我不能這樣做,因為我的按鈕在XAML中不存在,只在后面的代碼中存在。
那么命令綁定如何在代碼中起作用呢?
如果Button可以訪問Command,則接受的答案將很有用。 但是,在MVVM中,這些通常是分開的(視圖中的按鈕和視圖模型中的命令)。 在XAML中,您通常使用數據綁定來連接它(如問題中的示例)。
當我的動態Button無法找到Command時,我的程序給了我一個錯誤(因為它在一個完全不同的命名空間中)。 這就是我最終解決這個問題的方法:
SurfaceButton.SetBinding (Button.CommandProperty, new Binding("SaveReservationCommand"));
假設您將SurfaceButton命名為“SurfaceButton1”並且您可以訪問該命令的實例,則可以使用以下代碼:
SurfaceButton1.Command = 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);
希望它有所幫助...如果有什么不清楚,抱歉,這是我的第一篇文章:)
這有效
Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=UserControl, AncestorLevel=1}, Path=SaveReservationCommand}"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.