WP7 listbox selection changed event does not fire in a content control style
I have been scratching my head on why the selection changed event for a listbox does not fire. I have a panaroma items being created dynamically in the code behind... Kind of new to wpf/xaml
<Style x:Key="PanoramaItemStyle" TargetType="ContentControl">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ContentControl">
<Grid>
<controls:PanoramaItem x:Name="ItemLocationPanoramaItem" Header="{Binding TagName}">
<ListBox ItemsSource="{Binding ItemLocators}" Height="496" SelectedItem="{Binding SelectedItemLocation, Mode=TwoWay}" SelectionChanged="ItemLocatorsList_SelectionChanged" >
<ListBox.ItemsPanel>
<ItemsPanelTemplate >
<StackPanel Orientation="Vertical" ScrollViewer.VerticalScrollBarVisibility="Auto" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<StackPanel Orientation="Horizontal" Margin="0,0,0,17">
<StackPanel Width="311">
<TextBlock Text="{Binding Item.Name}" TextWrapping="Wrap" Style="{StaticResource PhoneTextLargeStyle}"/>
<TextBlock Text="{Binding Location.Description}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
</StackPanel>
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</controls:PanoramaItem>
<ContentPresenter/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="Foreground" Value="White"/>
</Style>
This is in the codebehind for the view.
public LocationGroups()
{
InitializeComponent();
LocationGroupsPanaroma.DefaultItem = LocationGroupsPanaroma.Items[0];
viewModel = this.DataContext as LocationGroupsViewModel;
CreateDynamicPanaromaItems();
}
private void CreateDynamicPanaromaItems()
{
foreach (Model.LocationGroup group in viewModel.LocationGroups)
{
if (group.TotalItems > 0)
{
PanoramaItem pi = new Pan开发者_开发问答oramaItem();
pi.Header = group.Name;
pi.Orientation = System.Windows.Controls.Orientation.Horizontal;
ItemLocationListViewModel itemLocationViewModel = viewModel[group.LocationGroupId];
pi.DataContext = itemLocationViewModel;
pi.Style = Resources["PanoramaItemStyle"] as Style;
LocationGroupsPanaroma.Items.Add(pi);
}
}
}
if you were using mvvm light you could do the following (fill your code in for the <> remarks:
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<mvvm:EventToCommand
Command="{Binding <yourviewmodel>.<yourrelaycommand>, Mode=OneWay, Source={StaticResource Locator}}" CommandParameter="{Binding SelectedValue, ElementName=<nameofyourlistbox>}"/>
</i:EventTrigger>
See my answers to this post and this post on how to dynamically generate panorama items and list boxes using mvvm, i.e. with no code behind.
精彩评论