当TextBox失去焦点时,将取消选择列表框项

时间:2014-09-21 11:13:01

标签: c# wpf textbox keyboard-events

在我的应用程序中,我有一个ListBox,其ListBoxItems呈现为TextBoxes。我想在TextBox获得键盘焦点时选择项目。我已向其应用了以下Trigger

<Trigger Property="IsKeyboardFocusWithin" Value="true">
    <Setter Property="IsSelected" Value="true" />
</Trigger>

然而,我不想要的是当TextBox失去焦点时取消选择的项目,这就是我目前得到的。这意味着我无法通过从TextBox中选择ComboBox来更改Template中的字体大小。

以上代码在ResourceDictionary文件的{{1}}中定义。

1 个答案:

答案 0 :(得分:3)

您可以使用Storyboard在焦点获得时选择项目,因此仅适用于选择

    <ListBox ...>
        <ListBox.ItemTemplate>
            <!-- your DataTemplate -->
        </ListBox.ItemTemplate>
        <ListBox.ItemContainerStyle>
            <Style TargetType="{x:Type ListBoxItem}">
                <Style.Triggers>
                    <EventTrigger RoutedEvent="GotKeyboardFocus">
                        <BeginStoryboard>
                            <Storyboard>
                                <BooleanAnimationUsingKeyFrames Storyboard.TargetProperty="IsSelected">
                                    <DiscreteBooleanKeyFrame Value="True" KeyTime="0:0:0"/>
                                </BooleanAnimationUsingKeyFrames>
                            </Storyboard>
                        </BeginStoryboard>
                    </EventTrigger>
                </Style.Triggers>
            </Style>
        </ListBox.ItemContainerStyle>
    </ListBox>

这样,当项目失去焦点时,项目将不会被自动取消选择

相关问题