5
我已經實現在http://msdn.microsoft.com/en-us/library/aa480736.aspx發現SortableSearchableList類,並增加了一個排序方法,如下所示:可排序的BindingList必然的DataGridView與方案排序
public void Sort(PropertyDescriptor prop, ListSortDirection direction)
{
ApplySortCore(prop, direction);
}
通過點擊任何的排序我的DataGridView當這個類的工作列標題,但我需要能夠以編程方式調用用於指定列的排序方法(使用在該實例中sortButton控制)。我在網上找到的一些代碼示例建議獲得列的PropertyDescriptor的,並且在傳遞到ApplySortCore方法。我還沒有得到那個工作。我可以得到我的任何或者的DataGridView的SortableSearchableList的PropertyDescriptorCollection性質,但似乎無法得到Find方法獲得的PropertyDescriptor爲我指定的列/成員。這裏是我的代碼的其餘部分:
namespace SortableBindingListTest
{
public partial class Form1 : Form
{
private SortableSearchableList<Tags> alarms = new SortableSearchableList<Tags>();
public Form1()
{
InitializeComponent();
alarms.Add(new Tags("some text", "1"));
alarms.Add(new Tags("more text", "2"));
alarms.Add(new Tags("another one", "3"));
dataGridView1.AutoGenerateColumns = false;
dataGridView1.AllowUserToAddRows = true;
dataGridView1.EditMode = DataGridViewEditMode.EditOnEnter;
dataGridView1.RowHeadersVisible = false;
dataGridView1.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill;
DataGridViewTextBoxColumn alarmColumn = new DataGridViewTextBoxColumn();
alarmColumn.DataPropertyName = "Alarm";
alarmColumn.Name = "Alarm";
alarmColumn.HeaderText = "Alarm";
DataGridViewTextBoxColumn messageColumn = new DataGridViewTextBoxColumn();
messageColumn.DataPropertyName = "Message";
messageColumn.Name = "Message";
messageColumn.HeaderText = "Message";
dataGridView1.Columns.Add(alarmColumn);
dataGridView1.Columns.Add(messageColumn);
dataGridView1.DataSource = alarms;
}
private void sortButton_Click(object sender, EventArgs e)
{
// try getting properties of BindingList
PropertyDescriptorCollection listProperties = TypeDescriptor.GetProperties(alarms);
PropertyDescriptor alarmProp = listProperties.Find("Alarm", false);
// prop is null at this point, so the next line fails
alarms.Sort(alarmProp, ListSortDirection.Ascending);
// try getting properties of DataGridView column
PropertyDescriptorCollection dgvProperties = TypeDescriptor.GetProperties(dataGridView1);
PropertyDescriptor columnProp = dgvProperties.Find("Alarm", false);
// columnProp is null at this point, so the next line also fails
alarms.Sort(columnProp, ListSortDirection.Ascending);
}
}
public class Tags : INotifyPropertyChanged
{
private string _alarm;
private string _message;
public event PropertyChangedEventHandler PropertyChanged;
public Tags(string alarm, string message)
{
_alarm = alarm;
_message = message;
}
public string Alarm
{
get { return _alarm; }
set
{
_alarm = value;
this.NotifyPropertyChanged("Alarm");
}
}
public string Message
{
get { return _message; }
set
{
_message = value;
this.NotifyPropertyChanged("Message");
}
}
private void NotifyPropertyChanged(string name)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
}
任何幫助將不勝感激。
謝謝,這作品! – 2012-04-30 14:09:57