WPF:当文本框具有焦点时,为列表框设置IsSelected,而不会丢失对LostFocus的选择 [英] WPF: Setting IsSelected for ListBox when TextBox has focus, without losing selection on LostFocus

查看:178
本文介绍了WPF:当文本框具有焦点时,为列表框设置IsSelected,而不会丢失对LostFocus的选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的模板中有ListBoxListBoxItems,因此它们包含TextBoxes

I've a ListBox with ListBoxItems with a template so they contain TextBoxes

TextBox聚焦时,我希望选择ListBoxItem.我找到的一种解决方案是这样的:

When the TextBox gets focused I want the ListBoxItem to be selected. One solution I've found looks like this:

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

这很好用,但是当TextBox失去焦点时,选择也是如此.

This works great, but when the TextBox loses focus so does the selection.

有办法防止这种情况发生吗?

Is there a way to prevent this from happening?

推荐答案

我发现最好的解决方案是没有代码的:

Best solution I've found to do this with no code behinde is this:

<Style TargetType="{x:Type ListBoxItem}">
    <Style.Triggers>
        <EventTrigger RoutedEvent="PreviewGotKeyboardFocus">
            <BeginStoryboard>
                <Storyboard>
                    <BooleanAnimationUsingKeyFrames
                        Storyboard.TargetProperty="(ListBoxItem.IsSelected)">

                        <DiscreteBooleanKeyFrame KeyTime="0" Value="True"/>
                    </BooleanAnimationUsingKeyFrames>
                </Storyboard>
            </BeginStoryboard>
        </EventTrigger>
    </Style.Triggers>
</Style>

这篇关于WPF:当文本框具有焦点时,为列表框设置IsSelected,而不会丢失对LostFocus的选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆