C# 聚焦ListBoxItem不会';不要更新它的样式
A有一个列表框,需要在某些情况下(例如,在显示搜索结果时)聚焦特定项目。这是通过附加属性完成的,使用以下函数:C# 聚焦ListBoxItem不会';不要更新它的样式,c#,wpf,user-interface,attached-properties,C#,Wpf,User Interface,Attached Properties,A有一个列表框,需要在某些情况下(例如,在显示搜索结果时)聚焦特定项目。这是通过附加属性完成的,使用以下函数: public static void OnElementIndexPropertyChanged (DependencyObject DObject, DependencyPropertyChangedEventArgs Args) { ListBox ListBoxControl = DObject as ListBox; if (ListBoxControl != n
public static void OnElementIndexPropertyChanged (DependencyObject DObject, DependencyPropertyChangedEventArgs Args)
{
ListBox ListBoxControl = DObject as ListBox;
if (ListBoxControl != null &&
(int)Args.NewValue != -1)
{
ListBoxControl.ScrollIntoView (ListBoxControl.Items[(int)Args.NewValue]);
ListBoxControl.UpdateLayout ();
var ListBoxItem = (ListBoxItem)ListBoxControl.ItemContainerGenerator.ContainerFromItem (ListBoxControl.Items[(int)Args.NewValue]);
ListBoxControl.SelectedItem = ListBoxItem;
ListBoxItem.Focus ();
}
}
现在,ListBoxControl确实获得了键盘焦点(如果我按住Alt键,它将在其周围显示一个虚线边框,并且它使用箭头键上下移动,它工作正常),但是样式不会更新。最后选定的项目将保留蓝色高亮显示,而新选定的项目不会更新为显示蓝色高亮显示。它仅在项目聚焦和突出显示之前第一次正常工作
除了手动更改背景/样式之外,还有其他方法吗?我习惯于将
SelectedItem
设置为实际项目,而不是该项目的容器。使用SelectedIndex
似乎更自然,因为您已经有了索引。通过将SelectedItem
行替换为以下内容,我可以选择使用样式的ListBox
:
ListBoxControl.SelectedIndex=(int)Args.NewValue代码>
p.S.
我应该补充一点,也许我没有完全理解这个问题,因为我想知道为什么您不只是使用SelectedIndex
而不是自定义附加属性来更改选择(可能是因为滚动不一样?)。感谢@chiunesughihara,我意识到我正在将SelectedItem
设置为容器,而不是实际项目。换线
ListBoxControl.SelectedItem = ListBoxItem;
到
已足够使其按预期工作。SelectedIndex已设置,但未正确聚焦项目。所以我选择了附加属性的方法。无论如何,您的内容让我意识到我是在将SelectedItem
设置为容器,而不是内容。我使用了ListBoxItem.Content
,现在它可以正常工作了。
ListBoxControl.SelectedItem = ListBoxItem.Content;