原文:WPF ListBoxItem模板中添加CheckBox选中问题

是这样的,需要一个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

最新文章

  1. Oracle碎碎念~1
  2. Appium scroll 滑动查找
  3. MySQL ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)的真正原因
  4. [perl]字符串转拼音首字母(支持多音字)
  5. LightOj1089(求点包含几个线段 + 线段树)
  6. java设置环境变量小工具
  7. jquery ready 延迟
  8. SQL Server 脚本
  9. 如何通过apt-get获得安装包的源码
  10. 欧拉工程第58题:Spiral primes
  11. 【转载】test和cmp比较
  12. nodejs个人配置
  13. HDU 3468 Treasure Hunting(BFS+网络流之最大流)
  14. JavaEE Tutorials (10) - Java持久化查询语言
  15. 搭建dnsmasq服务器,局域网内部解析
  16. Java经典编程题50道之二
  17. [APIO2010]
  18. 【DevOps敏捷开发动手实验】开源文档 v2015.2 stable 版发布
  19. 树莓派linux系统中显示隐藏文件的几种方法
  20. phpcms2008远程代码执行漏洞

热门文章

  1. thinkphp3.2.3 自动验证 正则验证
  2. 安卓 WebView加载本地图片时居中显示
  3. VMware Workstation 12 安装mac os x 10.11
  4. 想要搞BGM,没有歌曲链接怎么办?
  5. [Angular] Export directive functionalities by using &#39;exportAs&#39;
  6. [Angular] Wrap a third party lib into service
  7. centos7 rabbitmq安装/配置
  8. 学习游戏服务器开发必看,C++游戏服务器开发常用工具介绍
  9. PatentTips - Heterogeneous Parallel Primitives Programming Model
  10. [转至云风的博客]开发笔记 (2) :redis 数据库结构设计