Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop xaml element

Tags:

c#

xaml

I have an array of strings. For each of these strings, I'd like to create a seperate xaml element (<menuitem> is from an external library):

<MenuItem Header="Update">
  <MenuItem Header="arrayvalue1" Command="{Binding UpdateCommand}" />
  <MenuItem Header="arrayvalue2" Command="{Binding UpdateCommand}" />
  <MenuItem Header="arrayvalue3" Command="{Binding UpdateCommand}" />
</MenuItem>

Instead of hardcoding 3 elements, I'd like to create these from the array of strings.

Is this possible and if so, how?

like image 274
Bv202 Avatar asked Jul 25 '26 01:07

Bv202


2 Answers

MenuItem is an ItemsControl, so you can bind any collection to the ItemsSource property and it will generate the children for you. In the case of MenuItem, the children generated are also MenuItems. To apply bound values to properties on those children you can set an ItemContainerStyle which will be applied to each. Since the Command you want to use is on the top level DataContext you will need to use more of an indirect binding, which may be different depending on which technology you're using. Here's how it looks for WPF:

        <MenuItem Header="Update" ItemsSource="{Binding Strings}">
            <MenuItem.ItemContainerStyle>
                <Style TargetType="{x:Type MenuItem}">
                    <Setter Property="Command" Value="{Binding Path=DataContext.UpdateCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Menu}}}" />
                    <Setter Property="Header" Value="{Binding}" />
                </Style>
            </MenuItem.ItemContainerStyle>
        </MenuItem>
like image 192
John Bowen Avatar answered Jul 27 '26 14:07

John Bowen


What you're looking for is called an ItemsControl. You can use it to present a bunch of items in whatever form you like by adding an ItemTemplate to it.

like image 33
Jon Avatar answered Jul 27 '26 16:07

Jon