首页 > 解决方案 > 在c#中将所选项目作为当前项目

问题描述

我有一个绑定到 C# WPF 中的集合的列表框。当我搜索记录时,我想将所选项目移动到列表顶部并标记为选中。

这是我的代码:

var loc = lst_sub.Items.IndexOf(name);
lst_sub.SelectedIndex = loc;
lst_sub.Items.MoveCurrentToFirst();

标签: c#wpflistbox

解决方案


这可以使用一个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>

更多详情请参阅我的博文


推荐阅读