c# - 在c#中将所选项目作为当前项目
问题描述
我有一个绑定到 C# WPF 中的集合的列表框。当我搜索记录时,我想将所选项目移动到列表顶部并标记为选中。
这是我的代码:
var loc = lst_sub.Items.IndexOf(name);
lst_sub.SelectedIndex = loc;
lst_sub.Items.MoveCurrentToFirst();
解决方案
这可以使用一个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>
更多详情请参阅我的博文。
推荐阅读
- ios - iOS状态栏内的蓝牙图标
- java - RxJava 2 的 onErrorInsertItem?高级 rx 缓存逻辑
- azure - 无法在 Windows azure 上运行控制台应用程序
- c# - 如何确定在标准 MS DI 中实现接口 X 的服务?
- php - PHP 和 Mysql 没有回显我的变量
- javascript - 带有.map的索引数组在nodejs上不起作用
- amazon-web-services - 从 ec2 实例到其自己的公共 ip 的 aws 访问
- python - AttributeError:模块“tensorflow.python.keras”没有属性“模型”
- android - 图表中两个系列/折线图的交点
- openmp - MPI 资源特定实现