WPF绑定动态添加的控件

时间:2010-11-15 18:50:03

标签: wpf xaml

我在RibbonWindow的“Company”RibbonApplicationMenuItem中添加了一个代码:

  var reset = DataContext as ICompanies;
  if (reset != null)
  {

    // ToDo: Create interface to populate the mymenutems
    var mymenuitems = new List<string>();
    foreach (var item in mymenuitems)
    {
      var newbutton = new Button { Margin = new Thickness(2), Content = item };
      MenuItem_Company.Items.Add(newbutton);
    }
  }

我的XAML看起来像这样:

<ribbon:RibbonApplicationMenu ToolTipTitle="Application Menu">
    <ribbon:RibbonApplicationMenuItem 
        Header="Company"
        x:Name="MenuItem_Company"
        ImageSource="Images\LargeIcon.png">                     
    </ribbon:RibbonApplicationMenuItem>
</ribbon:RibbonApplicationMenu>

当我将新按钮添加到MenuItem_Company时,如何在代码中绑定它?我需要它绑定到我的datacontext中的属性。

谢谢, Eroc

1 个答案:

答案 0 :(得分:2)

var newbutton = new Button { Margin = new Thickness(2), Content = item };
Binding b = new Binding();
b.Source = reset;
b.Path = new PropertyPath("SomePropertyOnDataContext");
newButton.SetBinding(Button.IsEnabledProperty, b);

在代码中改变假设...但它应该让你知道从哪里开始......