C# Uwp Autosuggestbox OrderBy Displaymemberpath
我的autosuggestbox有一个行为,我必须按升序排列所有建议的列表项,这个行为将应用于整个应用程序中的一个常见样式的autosuggestbox。当我尝试简单地对对象本身进行排序时,效果很好,因为项目只是一个字符串列表。但是,当项目是一个对象列表,并且我想使用一个特定属性进行排序时,它就不适用于我。我使用DisplayMemberPath告诉它应该查找哪个属性。下面是我尝试使用的代码: 行为 XamlC# Uwp Autosuggestbox OrderBy Displaymemberpath,c#,xaml,uwp,sql-order-by,textchanged,C#,Xaml,Uwp,Sql Order By,Textchanged,我的autosuggestbox有一个行为,我必须按升序排列所有建议的列表项,这个行为将应用于整个应用程序中的一个常见样式的autosuggestbox。当我尝试简单地对对象本身进行排序时,效果很好,因为项目只是一个字符串列表。但是,当项目是一个对象列表,并且我想使用一个特定属性进行排序时,它就不适用于我。我使用DisplayMemberPath告诉它应该查找哪个属性。下面是我尝试使用的代码: 行为 Xaml 文本更改事件 private void AutoSuggestBox\u Text
文本更改事件
private void AutoSuggestBox\u TextChanged(AutoSuggestBox发送方、autosuggestboxtextchangedventargs args)
{
var abcc=新列表();
abcc.添加(“xyz”);
abcc.添加(“321”);
abcc.添加(“123”);
abcc.添加(“lopmjk”);
abcc.添加(“acb”);
sender.ItemsSource=abcc;
}
专用void AutoSuggestBox_TextChanged2(AutoSuggestBox发送方、AutoSuggestBoxTextChangedEventArgs参数)
{
var persons=新列表();
添加(新人员{Name=“xyz”,计数=1});
添加(新人员{Name=“321”,计数=2});
添加(新人员{Name=“123”,计数=3});
添加(新的人{Name=“lopmjk”,count=4});
添加(新人员{Name=“acb”,计数=5});
sender.ItemsSource=个人;
}
因此,我通过一个小实验找到了解决方案,我们可以使用GetValue()方法传入对象本身,然后它会按预期工作:
autoSuggestBox.ItemsSource = autoSuggestBox.Items.ToList().OrderBy(x => x.GetType().GetProperty(autoSuggestBox.DisplayMemberPath).GetValue(x)).ToList();
<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" />
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;
}
autoSuggestBox.ItemsSource = autoSuggestBox.Items.ToList().OrderBy(x => x.GetType().GetProperty(autoSuggestBox.DisplayMemberPath).GetValue(x)).ToList();