gpt4 book ai didi

wpf - Xaml中CollectionViewSource SortDescription的绑定(bind)PropertyName

转载 作者:行者123 更新时间:2023-12-03 20:23:33 26 4
gpt4 key购买 nike

这是我的 xaml,它告诉 collectionviewsource 排序属性名称。

<CollectionViewSource Source="{Binding Contacts}" x:Key="contactsCollection" Filter="CollectionViewSource_Filter">
<CollectionViewSource.SortDescriptions>
<scm:SortDescription PropertyName="DisplayName" />
</CollectionViewSource.SortDescriptions>
</CollectionViewSource>

上面的 xaml 工作正常,但我遇到的问题是我不知道如何为 SortDescription PropertyName 赋予变量值。我的 View 模型中有一个属性,它告诉要对哪个属性进行排序,但我无法将此属性绑定(bind)到 SortDescription 的 PropertyName 字段。

有什么办法吗?

最佳答案

您可以在后面的代码中设置排序描述。

XAML:

<Window.Resources>

<CollectionViewSource Source="{Binding People}" x:Key="_peopleCVS" />

</Window.Resources>

<StackPanel>
<ListBox
ItemsSource="{Binding Source={StaticResource _peopleCVS}}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=Name}" Margin="5,0"/>
<TextBlock Text="{Binding Path=Age}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<ComboBox SelectionChanged="ComboBox_SelectionChanged">
<ComboBoxItem>Age</ComboBoxItem>
<ComboBoxItem>Name</ComboBoxItem>
</ComboBox>
</StackPanel>

后面的代码:
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;

namespace CollectionViewSourceDemo
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();

People = new List<Person>();
People.Add(new Person("Bob", 34));
People.Add(new Person("Sally", 12));
People.Add(new Person("Joe", 56));
People.Add(new Person("Mary", 23));

DataContext = this;
}

public List<Person> People { get; private set; }

private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ComboBoxItem comboBoxItem = (sender as Selector).SelectedItem as ComboBoxItem;
string sortProperty = comboBoxItem.Content as string;
CollectionViewSource cvs = FindResource("_peopleCVS") as CollectionViewSource;
cvs.SortDescriptions.Clear();
cvs.SortDescriptions.Add(new SortDescription(sortProperty, ListSortDirection.Ascending));
}
}

public class Person
{
public Person(string name, int age)
{
Name = name;
Age = age;
}

public string Name { get; private set; }
public int Age { get; private set; }
}
}

关于wpf - Xaml中CollectionViewSource SortDescription的绑定(bind)PropertyName,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3035797/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com