Home > Back-end >  WPF Menu Item Selection
WPF Menu Item Selection

Time:09-23

I have a MenuItem which sub items is generated through a ItemsControl items source colletion. If I add MenuItems in the xaml, each individual item display a selection on it self when mouse over, see first image. On the collection bound item it also "selects the collection" and it also gets indented, see second image, how can I disable this?

XAML

<MenuItem 
Name="Template" 
Header="Startmall"/>
<MenuItem 
    Header="Symboler" 
    Name="CustomerSymbols">
    <MenuItem Header="Test1"/>
    <MenuItem Header="Test2"/>
    <MenuItem Header="Test3"/>
    <ItemsControl ItemsSource="{Binding CustomerSymbols}"/>

C#

//Populating CustomerSymbols on class initalization
private void LoadCustomerSymbols()
{
    List<string> files = Settings.CustomerFiles; // List of string files

    foreach(string file in files)
    { 
        MenuItem menuItem = new MenuItem();
        string fileName = Path.GetFileNameWithoutExtension(file);
        menuItem.Header = fileName;
        CustomerSymbols.Add(menuItem);
    }
}

MenuItem Single Selection

MenuItem Collection Selection

CodePudding user response:

This is not valid

<ItemsControl ItemsSource="{Binding CustomerSymbols}"/>

You can do it like this

<MenuItem Header="Symboler">
    <MenuItem.ItemsSource>
        <CompositeCollection>
            <MenuItem Header="Test1" />
            <MenuItem Header="Test2" />
            <MenuItem Header="Test3" />
            <CollectionContainer Collection="{Binding Source={StaticResource MyMenuItems}}" />
        </CompositeCollection>
    </MenuItem.ItemsSource>
</MenuItem>

Define MyMenuItems at one of MenuItem's parents' resources (ex. <Menu />)

Full example:

<Menu>
    <Menu.Resources>
        <CollectionViewSource x:Key="MyMenuItems" Source="{Binding CustomerSymbols}" />
    </Menu.Resources>
    <!--  other code  -->
    <MenuItem Header="Symboler">
        <MenuItem.ItemsSource>
            <CompositeCollection>
                <MenuItem Header="Test1" />
                <MenuItem Header="Test2" />
                <MenuItem Header="Test3" />
                <CollectionContainer Collection="{Binding Source={StaticResource MyMenuItems}}" />
            </CompositeCollection>
        </MenuItem.ItemsSource>
    </MenuItem>
    <!--  other code  -->
</Menu>
  • Related