2009-09-29 46 views
0

我有一个StackPanel多个Expander S:StackPanel中有多个扩展

<StackPanel Margin="0,10,0,0"> 
    <Expander Header="Test 1"> 
     <ListBox> 
      <ListBoxItem Content="Unit 1"/> 
      <ListBoxItem Content="Unit 2"/> 
     </ListBox> 
    </Expander> 
    <Expander Header="Test 2"> 
     <ListBox> 
      <ListBoxItem Content="Unit 3"/> 
      <ListBoxItem Content="Unit 4"/> 
     </ListBox> 
    </Expander> 
</StackPanel> 

我想要实现这些行为:

  • 一个或两个Expander(S)可以扩展
  • 只有一个Expander可能是活动的(更改标题背景)
  • 活动如果我选择另一Expander面板内但是如果我选择面板以外的其他Expander或其他控制活动Expander停留

我怎样才能做到这一点会改变吗?

回答

1

将它们添加到ListControl而不是StackPanel。 ListControls支持选择一个项目。

XAML:

<Window x:Class="ExpanderTest.Window1" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Height="300" Width="300"> 

    <Window.Resources> 

     <Style TargetType="ListBoxItem"> 
      <Style.Resources> 
       <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Red"/> 
       <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="Red"/> 
      </Style.Resources> 

     </Style> 

    </Window.Resources> 

    <StackPanel Margin="0,10,0,0"> 
     <ListBox SelectedIndex="1"> 
      <ListBoxItem HorizontalContentAlignment="Stretch"> 
       <Expander Header="Test 1"> 
        <ListBox> 
         <ListBoxItem Content="Unit 1"/> 
         <ListBoxItem Content="Unit 2"/> 
        </ListBox> 
       </Expander> 
      </ListBoxItem> 
      <ListBoxItem HorizontalContentAlignment="Stretch"> 
       <Expander Header="Test 2" > 
        <ListBox> 
         <ListBoxItem Content="Unit 3"/> 
         <ListBoxItem Content="Unit 4"/> 
        </ListBox> 
       </Expander> 
      </ListBoxItem> 
     </ListBox> 
    </StackPanel> 

</Window> 

后面的代码:

using System; 
using System.Windows; 
using System.Windows.Controls; 
using System.Windows.Media; 

namespace ExpanderTest 
{ 
    public partial class Window1 : Window 
    { 
     public Window1() 
     { 
      InitializeComponent(); 

      EventManager.RegisterClassHandler(typeof(UIElement), 
             GotFocusEvent, 
             new RoutedEventHandler(OnGotFocus)); 
     } 

     private static void OnGotFocus(object sender, RoutedEventArgs e) 
     { 
      // Check if element that got focus is contained by a listboxitem and 
      // in that case selected the listboxitem. 

      DependencyObject parent = e.OriginalSource as DependencyObject; 
      while (parent != null) 
      { 
       ListBoxItem clickedOnItem = parent as ListBoxItem; 
       if (clickedOnItem != null) 
       { 
        clickedOnItem.IsSelected = true; 
        return; 
       } 

       parent = VisualTreeHelper.GetParent(parent); 
      } 
     } 
    } 
} 

见我回答这个职位有什么背后的代码所做的:link text