Bv202
Bv202

Reputation: 4044

Loop xaml element

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?

Upvotes: 3

Views: 3364

Answers (2)

John Bowen
John Bowen

Reputation: 24453

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>

Upvotes: 3

Jon
Jon

Reputation: 3065

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.

Upvotes: 1

Related Questions