简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM