我有一個列表框,並在數據模板中有一個擴展器。如何使WPF Listbox子數據模板控件在單擊時選擇ListBoxItem容器?
如果我點擊Expander Header,擴展器展開內容區域,但不會使父級ListBoxItem選中。
如果我單擊擴展器的擴展內容區域,則會選擇父級ListBoxItem。
如何做到這一點,當點擊expanderHeader,內容變得擴大,並且父列表框選項被選中?
我有一個列表框,並在數據模板中有一個擴展器。如何使WPF Listbox子數據模板控件在單擊時選擇ListBoxItem容器?
如果我點擊Expander Header,擴展器展開內容區域,但不會使父級ListBoxItem選中。
如果我單擊擴展器的擴展內容區域,則會選擇父級ListBoxItem。
如何做到這一點,當點擊expanderHeader,內容變得擴大,並且父列表框選項被選中?
我遇到同樣的問題,並通過聽在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;
}
你不能使用Expanded
事件嗎?
像
<Expander Expanded="Expander_Expanded"
和
private void Expander_Expanded(object sender, RoutedEventArgs e)
{
parentListBox.Focus();
}
東西,你可以做的是擴展的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>
是的,這不是一件好事。我必須像自定義控件(如進度條等)仿效樹視圖/列表視圖...所以我需要所有組可以展開或摺疊... – Alex 2011-03-06 10:52:11
我意識到,這個問題已經回答了,但有一個更簡單的方法來實現這一期望的結果。您可以將Trigger
添加到ListBoxItem Style
將選擇ListBoxItem
每當一個元素的ItemTemplate
具有鍵盤焦點:
<Style.Triggers>
<Trigger Property="IsKeyboardFocusWithin" Value="True">
<Setter Property="IsSelected" Value="True"/>
</Trigger>
</Style.Triggers>
我真的很喜歡這個解決方案。沒有代碼,純粹是WPF。很乾淨@Sheridan – Jaime 2013-03-13 16:18:21
是的,但我如何訪問parentListboxItem? – Alex 2011-03-06 10:58:51