在内部ComboBox聚焦时选择ListBoxItem

App*_*ink 12 wpf xaml triggers listbox datatemplate

我有一个DataTemplate,它将是一个模板化的ListBoxItem,这个DataTemplate中有一个ComboBox,当它有焦点时我想要这个模板所代表的ListBoxItem被选中,这看起来对我来说.但遗憾的是它不起作用=(

所以这里真正的问题是在DataTemplate中是否可以ListBoxItem.IsSelected通过DataTemplate.Trigger?获取或设置属性的值?

<DataTemplate x:Key="myDataTemplate" 
              DataType="{x:Type local:myTemplateItem}">

 <Grid x:Name="_LayoutRoot">
     <ComboBox x:Name="testComboBox" />
 </Grid>

 <DataTemplate.Triggers>
     <Trigger Property="IsFocused" value="true" SourceName="testComboBox">
         <Setter Property="ListBoxItem.IsSelected" Value="true" />
     </Trigger>
 </DataTemplate.Triggers>

</DataTemplate>

<ListBox ItemTemplate="{StaticResource myDataTemplate}" />
Run Code Online (Sandbox Code Playgroud)

Nat*_*ium 9

我找到了解决问题的方法.

问题是当你对listboxitem有一个控件,并且单击了控件(比如输入文本或更改组合框的值)时,ListBoxItem不会被选中.

这应该做的工作:

public class FocusableListBox : ListBox
{
    protected override bool IsItemItsOwnContainerOverride(object item)
    {
        return (item is FocusableListBoxItem);
    }

    protected override System.Windows.DependencyObject GetContainerForItemOverride()
    {
        return new FocusableListBoxItem();
    }
}
Run Code Online (Sandbox Code Playgroud)

- >使用此FocusableListBox代替WPF的默认ListBox.

并使用此ListBoxItem:

public class FocusableListBoxItem : ListBoxItem
{
    public FocusableListBoxItem()
    {
        GotFocus += new RoutedEventHandler(FocusableListBoxItem_GotFocus);
    }


    void FocusableListBoxItem_GotFocus(object sender, RoutedEventArgs e)
    {
        object obj = ParentListBox.ItemContainerGenerator.ItemFromContainer(this);
        ParentListBox.SelectedItem = obj;
    }

    private ListBox ParentListBox
    {
        get
        {
            return (ItemsControl.ItemsControlFromItemContainer(this) as ListBox);
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

一个Treeview不也有这个问题,但这种方法不适用于一个工作Treeview,"原因SelectedItemTreeviewreadonly.所以,如果你能帮我看看Treeview,那么;-)


Jas*_*dge 9

我发现我更喜欢使用它:

<Style  TargetType="ListBoxItem">
    <Style.Triggers>
        <Trigger Property="IsKeyboardFocusWithin" Value="True">
             <Setter Property="IsSelected" Value="True"></Setter>
        </Trigger>
    </Style.Triggers>
</Style>
Run Code Online (Sandbox Code Playgroud)

简单,适用于所有listboxitems,无论内部是什么.

  • 您的答案有效但在单击按钮或任何其他控件后,我选择的索引重置为-1 (2认同)