更新时间:2022-09-14 15:12:51
是这样的,需要一个ListBox来展示照片,并添加一个选中的CheckBox.这就需要对ListBox的ItemTemplate的DataTemplate进行定制.添加一个Image和一个CheckBox.
大概是这样子的.
<Setter Property="ItemTemplate">
<Setter.Value>
<DataTemplate>
<Grid Width="250">
<Grid.RowDefinitions>
<RowDefinition Height="200"></RowDefinition>
<RowDefinition Height="20"></RowDefinition>
</Grid.RowDefinitions>
<Image Grid.Row="0" Source="{Binding Photo}" Width="220"/>
<CheckBox Grid.Row="1" Content="命中" IsChecked="{Binding IsTarget}"></CheckBox>
</Grid>
</DataTemplate>
</Setter.Value>
</Setter>
问题来了,当我选中CheckBox的时候,我希望ListBoxItem跳转到当前CheckBox所在的ListBoxItem上.如何实现?
主要有下面两种方法 :
1.
在Xaml中添加:
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<EventSetter Event="PreviewGotKeyboardFocus" Handler="SelectCurrentItem"/>
</Style>
</ListBox.ItemContainerStyle>
在.cs文件中添加
protected void SelectCurrentItem(object sender, KeyboardFocusChangedEventArgs e)
{
ListBoxItem item = (ListBoxItem)sender;
item.IsSelected = true;
}
在Xaml中添加:
<Style TargetType="{x:Type ListBoxItem}">
<Style.Triggers>
<Trigger Property="IsKeyboardFocusWithin" Value="true">
<Setter Property="IsSelected" Value="true" />
</Trigger>
</Style.Triggers>
</Style>
解释:
对于方法1:
http://msdn.microsoft.com/zh-cn/library/system.windows.uielement.iskeyboardfocuswithin(v=VS.90).aspx?ppud=4