Search code examples
c#wpfxamluser-controlsrouted-events

Parent-Child inside DataTemplate


In my MainWindow, I've got a ListBox whose ItemsSource is bound to an ObservableCollection of Layout POCO objects:

<ListBox x:Name="ListBox" ItemsSource="{Binding Layouts}">
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel IsItemsHost="True" Orientation="Horizontal" />
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
</ListBox>

Also, in the MainWindow, we define the visual representation of a Layout object using a UserControl (LayoutUserControl):

<DataTemplate DataType="{x:Type local:Layout}">
   <local:LayoutUserControl />
</DataTemplate>

When we add objects to the Layouts collection, we see new LayoutUserControls populate the ListBox. This is pretty straight forward.

Now, what I'd like to do, is somehow communicate from the MainWindow to the individual LayoutUserControls. Specifically, from the MainWindow, I want to call a single method on each of the LayoutUserControls... If I attempt to iterate through the ListBox's Items collection, all I get is a reference to the Layout objects, not the LayoutUserControls. Since the LayoutUserControls are defined in a DataTemplate, I don't have a named reference to access them...

Is there a WPF construct that supports this type of interaction from parent to child controls? RoutedEvents were my first thought, but they only support child to parent (bubble) communication. Perhaps commands are the way to go?

Any help would be appreciated.

Thanks!


Solution

  • Yes, there is a method which you should never use, it's the ItemContainerGenerator.

    You should, as you noted yourself, set up the communication differently, commands sound reasonable. Expose a command on the Layout and bind the UserControl to it. Or create an event and make the UserControl subscribe to it, then you can raise that.