Uwp Autosuggestbox订单通过Displaymemberpath

问题描述

我的autosuggestBox一个行为,我必须按升序对所有建议的列表项进行排序,并且此行为将应用于整个应用程序中1种常见样式的AutoSuggestBox。当我尝试简单地使用对象本身进行排序时,由于项目只是字符串列表,因此可以很好地工作。但是,当项目是对象列表时,我想使用1个特定属性进行排序,那么它对我不起作用。我正在使用displayMemberPath告诉它应该寻找哪个属性。下面是我尝试过的代码

行为

public class AutoSuggestSortBehavior : IBehavior
{
    public void Attach(DependencyObject associatedobject) => ((AutoSuggestBox) associatedobject).TextChanged += AutoSuggestSortBehavior_TextChanged;

    private void AutoSuggestSortBehavior_TextChanged(AutoSuggestBox sender,AutoSuggestBoxTextChangedEventArgs args)
    {
        var autoSuggestBox = sender;
        if(autoSuggestBox?.Items?.Count > 0 && args.Reason == AutoSuggestionBoxTextChangeReason.UserInput && !string.IsNullOrWhiteSpace(sender.Text))
        {
            if (!string.IsNullOrWhiteSpace(autoSuggestBox.displayMemberPath))
            {
                autoSuggestBox.ItemsSource = autoSuggestBox.Items.ToList().OrderBy(x => x.GetType().GetProperty(autoSuggestBox.displayMemberPath).Name).ToList();
            }
            else
            {
                autoSuggestBox.ItemsSource = autoSuggestBox.Items.ToList().OrderBy(x => x).ToList();
            }
        }            
    }
    public void Detach(DependencyObject associatedobject) => ((AutoSuggestBox) associatedobject).TextChanged -= AutoSuggestSortBehavior_TextChanged;
}

Xaml

<AutoSuggestBox
    Header="AutoSuggest"
    QueryIcon="Find"
    Text="With text,header and icon"
    TextChanged="AutoSuggestBox_TextChanged" />
<AutoSuggestBox
    displayMemberPath="Name"
    Header="AutoSuggest2"
    QueryIcon="Find"
    Text="With text,header and icon"
    TextChanged="AutoSuggestBox_TextChanged2" />

TextChanged事件

private void AutoSuggestBox_TextChanged(AutoSuggestBox sender,AutoSuggestBoxTextChangedEventArgs args)
    {
        var abcc = new List<string>();
        abcc.Add("xyz");
        abcc.Add("321");
        abcc.Add("123");
        abcc.Add("lopmjk");
        abcc.Add("acb");
        sender.ItemsSource = abcc;
    }

    private void AutoSuggestBox_TextChanged2(AutoSuggestBox sender,AutoSuggestBoxTextChangedEventArgs args)
    {
        var persons = new List<Person>();
        persons.Add(new Person { Name = "xyz",count = 1 });
        persons.Add(new Person { Name = "321",count = 2 });
        persons.Add(new Person { Name = "123",count = 3 });
        persons.Add(new Person { Name = "lopmjk",count = 4 });
        persons.Add(new Person { Name = "acb",count = 5 });
        sender.ItemsSource = persons;
    }

解决方法

所以我通过一个小实验就找到了解决方案,我们可以使用GetValue()方法传入对象本身,然后按预期工作:

autoSuggestBox.ItemsSource = autoSuggestBox.Items.ToList().OrderBy(x => x.GetType().GetProperty(autoSuggestBox.DisplayMemberPath).GetValue(x)).ToList();