问题
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?
回答1:
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>
来源:https://stackoverflow.com/questions/4640370/wp7-why-does-a-listbox-itemspanel-break-my-elementname-data-binding