wpf - 当子 TextBox 聚焦时设置 ListBoxItem.IsSelected

标签 wpf mvvm binding textbox listboxitem

我有一个典型的 MVVM 场景:
我有一个绑定(bind)到 StepsViewModels 列表的 ListBox。
我定义了一个 DataTemplate,以便将 StepViewModels 呈现为 StepViews。
StepView 用户控件有一组标签和文本框。

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

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

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

最佳答案

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

<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>

关于wpf - 当子 TextBox 聚焦时设置 ListBoxItem.IsSelected,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2960098/

相关文章:

c# - 如何覆盖 .NET 4 中动态对象的 PropertyDescriptor.GetValue 和 PropertyDescriptor.SetValue

ios - "The native class hasn' t been loading"错误与我的绑定(bind)

.net - 如何模拟慢速且无读取缓存的磁盘驱动器

.net - 如何使元素能够在其容器外绘制?

java - JSF 中的 'binding' 如何工作?

wpf - MVVMLight ViewModelLocator 注册数据服务

wpf - 在 F# WPF MVVM 应用程序中绑定(bind)到 TextBox 的 TextChanged 事件

WPF ListView 忽略 SelectedItem 更改

.net - 如何用给定枚举中的所有项目填充XAML中的WPF组合框?

c# - 如何以编程方式从 View 模型中选择 ListView 项?