Commanding & ItemsPanel

Topics: Prism v2 - Silverlight 3
Nov 28, 2009 at 9:33 AM

In one of my views I am using the following code:

        <ItemsControl
            x:Name="toolbox"
            ItemsSource="{Binding ButtonList}">
            <!--<ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel Orientation="Horizontal"/>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>-->
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Button Content="{Binding}" Margin="5"
                            cmd:Click.Command="{Binding DataContext.ClickCommand, ElementName=toolbox}"
                            cmd:Click.CommandParameter="{Binding}"/>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>

When I uncomment the ItemsPanel code, the command is no longer called. It works fine with the default panel. What's going on??

The ItemsSource is an ObservableCollection<string>.

I'm using Prism 2.1 on Silverlight 3

Nov 30, 2009 at 1:48 PM

Hi

The following extract is from the MSDN documentation on ElementName binding:

“When you set this property, the specified value must refer to an element in one of the following locations:

  • The current XAML namescope.

  • The XAML namescope of the templated parent if the binding target is in a data template or control template.”

When you use the ItemsPanelTemplate, you would be in the second mentioned scenario. Therefore, as a workaround, you can name the ItemsPanelTemplate and bind to it. The outcome is the following (I have smoke tested this and it works correctly):

<ItemsControl  x:Name="toolbox"   ItemsSource="{Binding ButtonList}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal" x:Name="stack"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Button Content="{Binding}" Margin="5"
                                cmd:Click.Command="{Binding DataContext.ClickCommand, ElementName=stack}"
                                cmd:Click.CommandParameter="{Binding}"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>
Please let me know if this helps.

Damian Schenkelman
http://blogs.southworks.net/dschenkelman

Dec 1, 2009 at 4:49 AM

Yes this works!

Thanks, Damian.