문제
나는있다 StackPanel
다수로 Expander
에스:
<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
(들) 확장 될 수 있습니다 - 단 하나
Expander
활성화 될 수 있습니다 (헤더 배경 변경) - 활성
Expander
다른 것을 선택하면 변경됩니다Expander
그러나 패널 내부는 다른 사람을 선택하면Expander
또는 패널 외부의 다른 컨트롤이 활성화됩니다Expander
머물러 있습니다
이것을 어떻게 달성 할 수 있습니까?
해결책
스택 패널 대신 ListControl에 추가하십시오. 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);
}
}
}
}
이 게시물에 대한 내 대답을 참조하십시오. 링크 텍스트
제휴하지 않습니다 StackOverflow