我有一个列表框,该列表框绑定到C#WPF中的集合。当我搜索记录时,我想将所选项目移到列表顶部并标记为已选中。
这是我的代码:
var loc = lst_sub.Items.IndexOf(name);
lst_sub.SelectedIndex = loc;
lst_sub.Items.MoveCurrentToFirst();
答案 0 :(得分:0)
这可以使用Behavior
类来处理...
public class perListBoxHelper : Behavior<ListBox>
{
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.SelectionChanged += AssociatedObject_SelectionChanged;
}
protected override void OnDetaching()
{
AssociatedObject.SelectionChanged -= AssociatedObject_SelectionChanged;
base.OnDetaching();
}
private static void AssociatedObject_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var listBox = sender as ListBox;
if (listBox?.SelectedItem == null)
{
return;
}
Action action = () =>
{
listBox.UpdateLayout();
if (listBox.SelectedItem == null)
{
return;
}
listBox.ScrollIntoView(listBox.SelectedItem);
};
listBox.Dispatcher.BeginInvoke(action, DispatcherPriority.ContextIdle);
}
}
用法...
<ListBox
Width="200"
Height="200"
ItemsSource="{Binding Items}"
SelectedItem="{Binding SelectedItem}">
<i:Interaction.Behaviors>
<vhelp:perListBoxHelper />
</i:Interaction.Behaviors>
</ListBox>
有关我的blog post的更多详细信息。