我已使用
在XAML中成功创建了一个下拉列表.XAML
<Grid>
<DockPanel>
<Menu>
<MenuItem Header="Menu">
<MenuItem Header="{Binding Path=ddlXferData1}" Command="{Binding Path=XferData}" Click="MenuItem_Click" IsCheckable="True"/>
<MenuItem Header="{Binding Path=ddlXferData2}" Command="{Binding Path=XferData}" Click="MenuItem_Click" IsCheckable="True"/>
<MenuItem Header="{Binding Path=ddlXferData3}" Command="{Binding Path=XferData}" Click="MenuItem_Click" IsCheckable="True"/>
<Separator />
<MenuItem Header="{Binding Path=ddlSkillData1}" Command="{Binding Path=SkillData}" Click="MenuItem_Click" IsCheckable="True"/>
<MenuItem Header="{Binding Path=ddlSkillData2}" Command="{Binding Path=SkillData}" Click="MenuItem_Click" IsCheckable="True"/>
<MenuItem Header="{Binding Path=ddlSkillData3}" Command="{Binding Path=SkillData}" Click="MenuItem_Click" IsCheckable="True"/>
</MenuItem>
</Menu>
</DockPanel>
</Grid>
.xaml.cs
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
MenuItem mnItem = (MenuItem) e.OriginalSource;
this.Model.menuItemSelected = (string) mnItem.Header;
}
从这里开始,命令XferData和SkillData用于引用基本上根据this.Model.menuItemSelected
执行某些操作的事件处理程序方法。所有这些都正常工作,以及我需要它的工作方式。
但是,现在我需要动态构建或创建菜单(下拉列表)选项。
我不是100%确定设计和实施动态下拉列表的最佳行动方案是什么:
我应该放入.xaml
<Button Name="MenuButton" Content="{Binding Path=btnMenu}" Command="{Binding Path=Menu}" Click="button1_Click" .../>
并在.xaml.cs中构建带选项的菜单
private void button1_Click(object sender, RoutedEventArgs e)
{
// Make the main menu.
Menu mainMenu = new Menu();
DockPanel dockPanel = new DockPanel();
dockPanel.Children.Add(mainMenu);
mainMenu.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
mainMenu.VerticalAlignment = System.Windows.VerticalAlignment.Top;
// Make the menu items.
MenuItem menuItem = new MenuItem();
.....
}
或
我应该动态构建XAML吗?
答案 0 :(得分:0)
不推荐,但你可以这样做:
//assuming you have Menu named MainMenu and you want to add Menu Item to it and Sub menu item to the item which you have just added
MenuItem MainItem = new MenuItem();
MainItem .Header = "Main Item";
this.MainMenu.Items.Add(MainItem);
MenuItem SubItem= new MenuItem();
SubItem.Header = "Sub Item";
SubItem.Click += new RoutedEventHandler(SubItem_Click);
MainItem.Items.Add(SubItem);