且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-09-14 15:12:51

原文: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