在 C# 中选择的项目作为当前项目
Selected item as Current Item in c#
我有一个列表框,它绑定到 C# WPF 中的一个集合。当我搜索记录时,我想将所选项目移动到列表顶部并标记为已选。
这是我的代码:
var loc = lst_sub.Items.IndexOf(name);
lst_sub.SelectedIndex = loc;
lst_sub.Items.MoveCurrentToFirst();
这可以使用 Behavior
class ...
来处理
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 的更多详细信息。
我有一个列表框,它绑定到 C# WPF 中的一个集合。当我搜索记录时,我想将所选项目移动到列表顶部并标记为已选。
这是我的代码:
var loc = lst_sub.Items.IndexOf(name);
lst_sub.SelectedIndex = loc;
lst_sub.Items.MoveCurrentToFirst();
这可以使用 Behavior
class ...
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 的更多详细信息。