当其内部 ComboBox 获得焦点时选择一个 ListBoxItem [英] Selecting a ListBoxItem when its inner ComboBox is focused
问题描述
我有一个 DataTemplate,它将是一个模板化的 ListBoxItem,这个 DataTemplate 有一个ComboBox 在其中,当它有焦点时,我想要这个模板的 ListBoxItem代表被选中,这对我来说是正确的.但遗憾的是它不起作用 =(
I have a DataTemplate that will be a templated ListBoxItem, this DataTemplate has a ComboBox in it which when it has focus I want the ListBoxItem that this template represents to become selected, this looks right to me. but sadly enough it doesn't work =(
所以这里真正的问题是在 DataTemplate 中是否可以获取或设置值ListBoxItem.IsSelected
属性通过 DataTemplate.Trigger
?
So the real question here is within a DataTemplate is it possible to get or set the value
of the ListBoxItem.IsSelected
property via a 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}" />
推荐答案
我找到了解决您问题的方法.
I found a solution for your problem.
问题是,当您在列表框项上有一个控件时,单击该控件(例如输入文本或更改组合框的值)时,列表框项不会被选中.
The problem is that when you have a control on your listboxitem, and the control is clicked (like for inputting text or changing the value of a combobox), the ListBoxItem does not get selected.
这应该可以完成工作:
public class FocusableListBox : ListBox
{
protected override bool IsItemItsOwnContainerOverride(object item)
{
return (item is FocusableListBoxItem);
}
protected override System.Windows.DependencyObject GetContainerForItemOverride()
{
return new FocusableListBoxItem();
}
}
--> 使用这个 FocusableListBox 代替 WPF 的默认 ListBox.
--> Use this FocusableListBox in stead of the default ListBox of WPF.
并使用这个 ListBoxItem:
And use this 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);
}
}
}
A Treeview
也有这个问题,但是这个解决方案不适用于 Treeview
,因为 Treeview 的
SelectedItem
是 只读
.因此,如果您可以帮助我解决 Treeview 问题,请 ;-)
A Treeview
does also have this problem, but this solution does not work for a Treeview
, 'cause SelectedItem
of Treeview
is readonly
.
So if you can help me out with the Treeview please ;-)
这篇关于当其内部 ComboBox 获得焦点时选择一个 ListBoxItem的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!