简体   繁体   English

在 c# 中选择的项目为当前项目

[英]Selected item as Current Item in c#

I have a list box which is bound to a collection in C# WPF.我有一个列表框,它绑定到 C# WPF 中的集合。 When I search for a record I want to move the selected item to the top of the list and mark as selected.当我搜索记录时,我想将所选项目移动到列表顶部并标记为选中。

Here is my code:这是我的代码:

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

This can be handled using a Behavior class...这可以使用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);
    }
}

Usage...用法...

<ListBox
    Width="200"
    Height="200"
    ItemsSource="{Binding Items}"
    SelectedItem="{Binding SelectedItem}">
    <i:Interaction.Behaviors>
        <vhelp:perListBoxHelper />
    </i:Interaction.Behaviors>
</ListBox>

More details on my blog post .更多详情请参阅我的博文

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM