[英]Dynamically add radiobuttons in submenu in C# WPF
I would like to implement a dynamical menu in my application, written in C# and using WPF. 我想在我的应用程序中使用C#编写并使用WPF实现动态菜单。
MenuSubSerialPortSelect.Items.Clear();
foreach (string element in GlobalVars.ActualSerialPorts)
{
MenuItem item = new MenuItem();
item.Header = element;
MenuSubSerialPortSelect.Items.Add(item);
}
The sub-menu adding is functional, but how can I add some radio buttons in this style? 子菜单添加功能正常,但是如何添加这种样式的单选按钮?
I've read some websites that described that there must be used another "template", but I can't find a matched solution for me. 我读过一些网站,描述必须使用另一个“模板”,但是我找不到适合我的解决方案。
The attribute item.IsCheckable = true;
属性
item.IsCheckable = true;
is not a solution for me -- the entries must be blocked against each other. 对我来说不是解决方案-条目必须相互阻止。
It would be great if somebody could give me a tip on how to do that. 如果有人可以给我一些提示,那将是很棒的。
Try this 尝试这个
<Window x:Class="Stackoverflow.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Stackoverflow"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<RadioButton x:Key="RadioButton" HorizontalAlignment="Center"
GroupName="MyGroup" IsHitTestVisible="False"/>
<Style TargetType="MenuItem">
<Setter Property="Icon" Value="{StaticResource RadioButton}"/>
<EventSetter Event="Click" Handler="MenuItem_Click" />
</Style>
</Window.Resources>
<Grid Background="Red">
<Grid.ContextMenu>
<ContextMenu>
<MenuItem Header="Print"/>
<MenuItem Header="Save"/>
<MenuItem Header="Open"/>
<MenuItem Header="Delete"/>
<MenuItem Header="Update"/>
</ContextMenu>
</Grid.ContextMenu>
</Grid>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModel();
}
private void MenuItem_Click(object sender, System.Windows.RoutedEventArgs e)
{
MenuItem menuItem = sender as MenuItem;
if (menuItem != null)
{
RadioButton rb = menuItem.Icon as RadioButton;
if (rb != null)
{
rb.IsChecked = true;
}
}
}
}
Here i just have static menuitems. 在这里,我只是静态菜单项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.