【问题标题】:Dynamically add radiobuttons in submenu in C# WPF在 C# WPF 的子菜单中动态添加单选按钮
【发布时间】:2014-07-28 04:03:57
【问题描述】:

我想在我的应用程序中实现一个动态菜单,用 C# 编写并使用 WPF。

MenuSubSerialPortSelect.Items.Clear();

foreach (string element in GlobalVars.ActualSerialPorts)
{   
    MenuItem item = new MenuItem();

    item.Header = element;

    MenuSubSerialPortSelect.Items.Add(item); 
}

子菜单添加是功能性的,但是如何添加一些这种风格的单选按钮?

我读过一些网站描述必须使用另一个“模板”,但我找不到适合我的解决方案。

item.IsCheckable = true; 属性不是我的解决方案——条目必须相互阻止。

如果有人能告诉我如何做到这一点,那就太好了。

【问题讨论】:

    标签: c# wpf radio-button menuitem


    【解决方案1】:

    试试这个

    <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;
                }
            }
        }
    }
    

    这里我只有静态菜单项。

    【讨论】:

    • 谢谢,但我需要动态项目。在程序启动时(例如),我扫描了可用的串行端口。计数和名称是动态的。
    • 您所要做的就是应用这种样式并处理点击事件。我不关心标题是静态的还是动态的。我很着急,所以只使用了静态项目
    • 好的,它现在正在运行 :) 谢谢你的剪辑!
    猜你喜欢
    • 2013-02-20
    • 2021-12-25
    • 2011-01-04
    • 2018-02-05
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多