Xaml loop element

I have an array of strings. For each of these lines, I would like to create a separate xaml element ( <menuitem>

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 would like to create them from an array of strings.

Is this possible, and if so, how?

+3


source to share


2 answers


MenuItem is an ItemsControl, so you can bind any collection to the ItemsSource property and generate children for you. In the case of MenuItem, the generated children are also MenuItems. To apply bound values ​​to the properties of these children, you can set the ItemContainerStyle to apply to each of them. Since the command you want to use is at the top level of the DataContext, you will need to use more indirect binding, which may differ depending on the technology you are using. This is what WPF looks like:



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

      

+3


source


What you are looking for is called ItemsControl . You can use it to present a bunch of items in any form you want by adding an ItemTemplate to it.



+1


source







All Articles