gpt4 book ai didi

wpf - 在其内部 ComboBox 获得焦点时选择 ListBoxItem

转载 作者:行者123 更新时间:2023-12-04 00:49:02 24 4
gpt4 key购买 nike

我有一个 DataTemplate,它将是一个模板化的 ListBoxItem,这个 DataTemplate 有一个
其中的 ComboBox 当它有焦点时我想要这个模板的 ListBoxItem
代表被选中,这对我来说是正确的。但遗憾的是它不起作用=(

所以这里真正的问题是在 DataTemplate 中是否可以获取或设置值
ListBoxItem.IsSelected属性(property)通过 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}" />

最佳答案

我为您的问题找到了解决方案。

问题是,当您在 listboxitem 上有一个控件,并且单击该控件时(例如输入文本或更改组合框的值),ListBoxItem 不会被选中。

这应该可以完成这项工作:

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。

并使用这个 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);
}
}

}

一个 Treeview也有这个问题,但是这个解决方案对 Treeview 不起作用, 因为 SelectedItemTreeviewreadonly .
所以,如果你能帮我解决 Treeview 问题,请 ;-)

关于wpf - 在其内部 ComboBox 获得焦点时选择 ListBoxItem,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1459786/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com