curiousity
curiousity

Reputation: 4741

Bind menu items to a list

I have a list of strings that holds the names of menu items:

List<string> namesStorage;

How do I bind this list as collection in XAML?
Right now I have wrote this is part, which already works:

<StackPanel Orientation="Vertical">
    <MenuItem Header="MenuItem1" Command="{Binding Command1}" />
    <MenuItem Header="MenuItem2" Command="{Binding Command1}" />
</StackPanel>

This items must have one command (different arguments will be set in the view model).
But I think this is not a good way to set every MenuItem in XAML - It is ok now for two items but I wonder how to make a universal decision for any number of this menu items. I have created a list that holds names but how to bind it (and keep a commands)?

Upvotes: 1

Views: 1562

Answers (1)

Philip W
Philip W

Reputation: 791

After setting the correct DataContext, this should work:

    <ItemsControl ItemsSource="{Binding namesStorage}" x:Name="ItemsControlName">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <MenuItem Header="{Binding}" Command="{Binding ElementName=ItemsControlName, Path=DataContext.Command1}"/>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>

Edit: Removed Parent-Stackpanel as suggested in the comments

Upvotes: 3

Related Questions