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

I have a Windows Phone 7 ListBox that binds to a list of integers. I use the MVVM Light template by default, 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> 

Displays a vertical list of integers inside buttons. If you press any of them, the following command code will execute and display a pop-up window: new RelayCommand<int>(i => MessageBox.Show("Test" + i));

However, if I simply add the following XAML to change the horizontal list, data binding 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 tried some other binding types for EventToCommand . For example, specifying my ViewModel as a static resource. It works, but less perfect than the example above.

Why does this ItemsPanel break data binding?

+3
source share
1 answer

This is a known issue with Silverlight 3 . To get around this, wrap the 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 instead:

 <ListBox ItemsSource="{Binding MyData}"> <ListBox.ItemTemplate> <DataTemplate> <local:MyUserControl /> </DataTemplate> </ListBox.ItemTemplate> </ListBox> 
+2
source

Source: https://habr.com/ru/post/1339124/


All Articles