如何使WPF Listbox子datatemplate控件在单击时选择ListBoxItem容器?

时间:2011-03-04 13:11:25

标签: .net wpf listbox listboxitem childcontrol

我有一个列表框,在datatemplate中我有一个扩展器。

如果我单击Expander Header,扩展器将展开内容区域,但不会选择父ListBoxItem。

如果单击Expander的Expanded Content Zone,则会选择父ListBoxItem。

如何在单击expandderHeader时进行扩展,内容将展开并且父列表框项被选中?

4 个答案:

答案 0 :(得分:7)

我意识到这个问题已得到解答,但有一种更简单的方法可以实现这个理想的结果。您可以向Trigger添加ListBoxItem Style,只要其ListBoxItem中的某个元素具有键盘焦点,就会选择ItemTemplate

<Style.Triggers> 
  <Trigger Property="IsKeyboardFocusWithin" Value="True"> 
    <Setter Property="IsSelected" Value="True"/> 
  </Trigger> 
</Style.Triggers>

有关详细信息,请查看MSDNpost1post2

答案 1 :(得分:1)

我遇到了同样的问题并通过侦听ListBox上的PreviewGotKeyboardFocus事件来处理它。当焦点更改时,可视树会查找ListBoxItem并选择它:

    private void ListBox_PreviewGotKeyboardFocus( object sender, KeyboardFocusChangedEventArgs e )
    {
        if( e.NewFocus is FrameworkElement )
        {
            ListBoxItem item = ( e.NewFocus as FrameworkElement ).FindParent<ListBoxItem>();
            if( item != null && !item.IsSelected )
            {
                item.IsSelected = true;
            }
        }
    }

    public static T FindParent<T>( this FrameworkElement element ) where T : FrameworkElement
    {
        DependencyObject current = element;

        while( current != null )
        {
            if( current is T )
            {
                return ( T ) current;
            }

            current = VisualTreeHelper.GetParent( current );
        }

        return null;
    }

答案 2 :(得分:0)

你不能使用Expanded事件吗?

类似

<Expander Expanded="Expander_Expanded"

private void Expander_Expanded(object sender, RoutedEventArgs e)
{
    parentListBox.Focus();
}

答案 3 :(得分:0)

您可以做的是将Expander的IsExpanded属性直接与ListBoxItem的IsSelected属性绑定。 但这意味着,你只需选择扩展器扩展的项目...... 这也意味着未选择的项目永远不会扩展。

示例:

  <ListBox>
    <ListBox.ItemTemplate>
      <DataTemplate>
        <Expander IsExpanded="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBoxItem}}, Path=IsSelected}">
          <TextBlock Text="bla bla" />
        </Expander>
      </DataTemplate>
    </ListBox.ItemTemplate>
    <ListBox.Items>
      <DataObject />
      <DataObject />
    </ListBox.Items>
  </ListBox>