在C#中选择了当前项目作为当前项目

时间:2020-06-04 06:06:03

标签: c# wpf listbox

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

这是我的代码:

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

1 个答案:

答案 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的更多详细信息。

相关问题