我有一个典型的 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/