聚焦子文本框时设置 ListBoxItem.IsSelected [英] Set ListBoxItem.IsSelected when child TextBox is Focused

查看:30
本文介绍了聚焦子文本框时设置 ListBoxItem.IsSelected的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个典型的 MVVM 场景:我有一个绑定到 StepsViewModel 列表的 ListBox.我定义了一个 DataTemplate,以便 StepViewModels 呈现为 StepViews.StepView UserControl 有一组标签和文本框.

I have a typical MVVM scenario: I have a ListBox that is binded to a List of StepsViewModels. I define a DataTemplate so that StepViewModels are rendered as StepViews. The StepView UserControl have a set of labels and TextBoxs.

我想要做的是选择在文本框聚焦时包装 StepView 的 ListBoxItem.我尝试使用以下触发器为我的文本框创建样式:

What I want to do is to select the ListBoxItem that is wrapping the StepView when a textBox is focused. I've tried to create a style for my TextBoxs with the following trigger:

<Trigger Property="IsFocused" Value="true">
    <Setter TargetName="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBoxItem}}}" Property="IsSelected" Value="True"/>
</Trigger>

但是我收到一条错误消息,告诉我 TextBox 没有 IsSelected 属性.我现在知道,但目标是一个 ListBoxItem.我怎样才能让它工作?

But I get an error telling me that TextBoxs don't have an IsSelected property. I now that but the Target is a ListBoxItem. How can I make it work?

推荐答案

有一个只读属性 IsKeyboardFocusWithin,如果有任何孩子获得焦点,该属性将设置为 true.您可以使用它在触发器中设置 ListBoxItem.IsSelected:

There is a read-only property IsKeyboardFocusWithin that will be set to true if any child is focused. You can use this to set ListBoxItem.IsSelected in a Trigger:

<ListBox ItemsSource="{Binding SomeCollection}" HorizontalAlignment="Left">
    <ListBox.ItemContainerStyle>
        <Style TargetType="{x:Type ListBoxItem}">
            <Style.Triggers>
                <Trigger Property="IsKeyboardFocusWithin" Value="True">
                    <Setter Property="IsSelected" Value="True" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </ListBox.ItemContainerStyle>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBox Width="100" Margin="5" Text="{Binding Name}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

这篇关于聚焦子文本框时设置 ListBoxItem.IsSelected的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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