您的位置:首页 > 其它

WPF ListBoxItem模板中添加CheckBox选中问题

2014-03-13 23:46 344 查看
是这样的,需要一个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;
}

2.
在Xaml中添加:

<Style TargetType="{x:Type ListBoxItem}">
<Style.Triggers>
<Trigger Property="IsKeyboardFocusWithin" Value="true">
<Setter Property="IsSelected" Value="true" />
</Trigger>
</Style.Triggers>
</Style>

问题解决.

解释:

对于方法1:


UIElement.PreviewGotKeyboardFocus 事件

在此元素聚焦于键盘时发生。由于此事件使用隧道路由,因此具有焦点的元素可能是子元素,而不是实际附加事件处理程序的元素。 请检查事件数据中的 Source 以确定实际具有焦点的元素。
http://msdn.microsoft.com/zh-cn/library/system.windows.uielement.previewgotkeyboardfocus.aspx
对于方法2:


UIElement.IsKeyboardFocusWithin 属性

获取一个值,该值指示键盘焦点是否位于元素或其可视树子元素内的任意位置。这是一个依赖项属性。
http://msdn.microsoft.com/zh-cn/library/system.windows.uielement.iskeyboardfocuswithin(v=VS.90).aspx?ppud=4
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息