0

我有一个绑定到数据网格的可观察集合...我想通过单击标题对数据网格进行排序。这是一个动态数据。这是我的代码

namespace SLSortObservableCollection
{
    public partial class MainPage : UserControl
    {
        //ObservableCollection<int> NumData = new ObservableCollection<int>();
       // ObservableCollection<string> StrData = new ObservableCollection<string>();

    public MainPage()
    {
        InitializeComponent();

       ObservableCollection<int> NumData = new ObservableCollection<int>();
    ObservableCollection<string> StrData = new ObservableCollection<string>();
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        Random ra = new Random();
        for (int i = 0; i < 10; i++)
        {
            int num = ra.Next(1000);
            NumData.Add(num);

        }
        try
        {

            dataGrid1.ItemsSource = null;
            dataGrid1.ItemsSource = NumData;
        }
        catch (Exception ex) { MessageBox.Show(ex.ToString()); }
    }

    private void button2_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            StringBuilder builder = new StringBuilder();
            Random random = new Random();
            char ch;
            for (int i = 0; i < 5; i++)
            {
                ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
                builder.Append(ch);
                StrData.Add(builder.ToString());
            }

            dataGrid1.ItemsSource = StrData;
        }
        catch (Exception ex) { MessageBox.Show(ex.ToString()); }
    }

}  

}
4

1 回答 1

1

ObservableCollection 根本不支持排序。如果这不是silverlight,您也许可以使用CollectionView 做一些事情。

实际上,您可能必须使用 SortableCollection 的自定义扩展。有几个这样飞来飞去,只要搜索“sortable observableCollection”

一些帮助您入门的实现

http://kiwigis.blogspot.de/2010/03/how-to-sort-obversablecollection.html

http://elegantcode.com/2009/05/14/write-a-sortable-observablecollection-for-wpf/

http://sortablecollection.codeplex.com/

于 2012-04-23T08:18:45.137 回答