我有一个可绑定到datagrid的可观察集合...我想通过单击标题对数据网格进行排序。这是一个动态数据。这是我的代码
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()); }
}
}
}
答案 0 :(得分: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/