2012-01-10 69 views
1

我为我的菜单控件做了一个样式,现在我想为所有menuItems使用该样式,但在文本框中使用不同的文本。我想知道如果我可以使用List来填充绑定元素...我试过但它不起作用...我错过了什么,或者我必须使用别的东西吗?是否有可能使用列表在菜单控件中进行绑定?

List<string> itemArray = new List<string>(); 
     itemArray.Add("label1"); 
     itemArray.Add("label2"); 
     itemArray.Add("label3"); 
     Binding binding = new Binding(); 
     binding.Path = new PropertyPath("itemArray"); 

     this.menu1.SetBinding(TextBox.TextProperty, binding); 

和风格的一个部分,如果它可以帮助...:

<Setter.Value> 
    <ControlTemplate TargetType="{x:Type MenuItem}"> 
     <Grid> 
      <Border Name="MainBorder" BorderThickness="2,2,2,0" > 
       <Grid> 
        <TextBlock Text="{Binding Path=itemArray}" Margin="30,10,0,0" FontFamily="Arial" FontSize="14" FontWeight="Bold" /> 
        <Image Width="15" Height="15" Source="image.PNG" Margin="-100,0,0,0" /> 
       </Grid> 
      </Border> 
     </Grid> 
    </ControlTemplate> 
</Setter.Value> 
+0

请参阅[MenuItem](http://msdn.microsoft.com/en-us/library/system.windows.controls.menuitem.aspx)上的MSDN文档中的备注部分,以获取其HeaderedItemsControl功能的概述以及如何使用MenuItems进行数据绑定。 – Clemens 2012-01-10 22:07:06

回答

1

你试图文本元素绑定到List<T>,这将导致该类型名称。如果您需要的菜单,从对象列表填充自身,考虑菜单的ItemsSource属性绑定到该列表:

 <Menu ItemsSource="{Binding ListOfItems}"> 
     <Menu.ItemTemplate> 
      <DataTemplate> 
       <MenuItem Header="{Binding Text}" Command="{Binding Command}" /> 
      </DataTemplate> 
     </Menu.ItemTemplate> 
    </Menu> 

在这个例子中,每个列表项是用Text属性的对象,显示了作为显示字符串和Command属性,该属性是实现ICommand的对象。当用户选择一个菜单项时,该列表项的Command.Execute方法被调用;你可以使用类似RelayCommandReactiveCommand这样的方法调用。

这允许平面菜单;对于分层菜单,你必须做一些不同的事情。

相关问题