问题描述
我有一个DataTemplate,它将成为模板化的ListBoxItem,该DataTemplate具有一个在其中具有焦点的ComboBox时,我想要该模板的ListBoxItem代表已被选中,这在我看来很正确.但可悲的是,它不起作用=(
I have a DataTemplate that will be a templated ListBoxItem, this DataTemplate has aComboBox in it which when it has focus I want the ListBoxItem that this templaterepresents 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 valueof 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.
问题是,当您在listboxitem上有一个控件并单击该控件时(例如,用于输入文本或更改组合框的值),ListBoxItem不会被选中.
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
是readonly
.因此,如果您可以通过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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!