WPF: Binding to commands in code behind

后端 未结 4 1171
梦如初夏
梦如初夏 2021-01-01 23:23

I have a WPF Microsoft Surface Application and I\'m using MVVM-Pattern.

I have some buttons that are created in code behind and I would like to bind commands to them

4条回答
  •  太阳男子
    2021-01-01 23:49

    I took the code from the link posted by Anvaka as template. I use RadMenuItem of Telerik, but surely you can use any other component that expose Command property.

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

    Hope it helps ... and if something is not clear, sorry, it's my first post :)

提交回复
热议问题