Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WP7: Why does a ListBox.ItemsPanel break my ElementName data binding?

I have a Windows Phone 7 ListBox that binds to a list of integers. I am using the default MVVM Light template, so there is a ViewModel class that contains data and a simple RelayCommand. Here is the ListBox:

<ListBox ItemsSource="{Binding MyData}">
    <ListBox.ItemTemplate>
        <DataTemplate>                        
            <Button Content="{Binding}">
                <i:Interaction.Triggers>
                    <i:EventTrigger EventName="Click">
                        <cmd:EventToCommand Command="{Binding ElementName=ContentGrid, Path=DataContext.TestCommand}"
                                            CommandParameter="{Binding}" />
                    </i:EventTrigger>
                </i:Interaction.Triggers>
            </Button>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

This displays a vertical list of integers inside buttons. If you click any of them, the following command code executes and shows a pop-up: new RelayCommand<int>(i => MessageBox.Show("Test" + i));

However, if I simply add the following XAML to change to a horizontal list, the databinding fails. Nothing happens when you click the button and no error messages are written to the Output window.

<ListBox.ItemsPanel>
    <ItemsPanelTemplate>
        <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" />
    </ItemsPanelTemplate>
</ListBox.ItemsPanel>

I have tried some other types of binding for the EventToCommand. For example, specifying my ViewModel as a static resource. It works, but is less ideal than the example above.

Why does that ItemsPanel break the databinding?

like image 597
user10789 Avatar asked Jan 26 '26 09:01

user10789


1 Answers

This is a known problem with Silverlight 3. To work around this, wrap your DataTemplate in a UserControl:

    <UserControl x:Class="SilverlightApplication.MyUserControl">
        <Button Content="{Binding}">
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="Click">
                    <cmd:EventToCommand Command="{Binding ElementName=ContentGrid, Path=DataContext.TestCommand}"
                                        CommandParameter="{Binding}" />
                </i:EventTrigger>
            </i:Interaction.Triggers>
        </Button>
    </UserControl>

And use it instead:

<ListBox ItemsSource="{Binding MyData}">
    <ListBox.ItemTemplate>
        <DataTemplate>                        
            <local:MyUserControl />
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
like image 135
decyclone Avatar answered Jan 27 '26 22:01

decyclone



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!