选定的项目作为c#中的当前项目

问题描述 投票:0回答:1

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

这是我的代码。

var loc = lst_sub.Items.IndexOf(name);
lst_sub.SelectedIndex = loc;
lst_sub.Items.MoveCurrentToFirst();
c# wpf listbox
1个回答
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>

更多的细节在我的 博文.

© www.soinside.com 2019 - 2024. All rights reserved.