在C#WPF的子菜单中动态添加单选按钮
我想在我的应用程序中实现一个动态菜单,用C#编写,使用WPF在C#WPF的子菜单中动态添加单选按钮,c#,wpf,radio-button,menuitem,C#,Wpf,Radio Button,Menuitem,我想在我的应用程序中实现一个动态菜单,用C#编写,使用WPF MenuSubSerialPortSelect.Items.Clear(); foreach (string element in GlobalVars.ActualSerialPorts) { MenuItem item = new MenuItem(); item.Header = element; MenuSubSerialPortSelect.Items.Add(item); } “添加
MenuSubSerialPortSelect.Items.Clear();
foreach (string element in GlobalVars.ActualSerialPorts)
{
MenuItem item = new MenuItem();
item.Header = element;
MenuSubSerialPortSelect.Items.Add(item);
}
“添加”子菜单是功能性的,但是如何添加这种样式的单选按钮
我读过一些网站描述必须使用另一个“模板”,但我找不到匹配的解决方案
属性item.IsCheckable=true
对我来说不是一个解决方案——条目必须相互阻止
如果有人能告诉我怎么做,那就太好了。试试这个
<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>
这里我只有静态菜单项。谢谢,但我需要动态项。在程序启动时(例如),我扫描了可用的串行端口。计数和名称是动态的。您所要做的就是应用此样式并处理单击事件。我不管标题是静态的还是动态的。我当时很匆忙,所以刚刚使用了静态itemsOk,它现在正在运行:)谢谢你的剪贴!
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;
}
}
}
}