綜合應用WPF/WCF/WF/LINQ之三十九:實現一個簡單的DataGrid之獲取某格的原始(或當前)行(或列)的Index

爲什麼這些Index很難取得呢?這是因爲ListView控件的RoutedEventArgs中的信息太少了,而且這個控件又支持Column的直接拖動重排,以及數據的排序,這就導致行、列的Index有原始和當前值兩個版本。
  在這幾個Index中,又尤其以SourceColumnIndex最難取得。由於本程序的DataTemplate都是以XamlReader.Load的方式實現的,如下:
    1 string content = string.Format("<common:DataGridButton Name=\"Button{0}\" ColumnIndex=\"{1}\" Content=\"{2}\" Value=\"{{Binding Path={3}}}\" />", i.ToString(), i.ToString(), column.ButtonContent, column.ButtonValuePath);
    2 column.CellTemplate = XamlReader.Load(XmlReader.Create(new StringReader(string.Format(template, content)))) as DataTemplate;
  這就給我們一個機會,可以隨意指定嵌入控件的各種屬性。我們可以將SourceColumnIndex的值保存在嵌入控件的某個屬性,如Tag屬性中,或者乾脆在繼承於原始控件的自定義控件中加入一個ColumnIndex的屬性,用於保存SourceColumnIndex的值。
  這樣處理後,我們即可在該控件中註冊一個事件,並在RoutedEventHandler指定的方法中,使用(e.OriginalSource as DataGridButton).ColumnIndex的方式來取得當前格的SourceColumnIndex。有了SourceColumnIndex之後,其它各個Index就比較容易得到了:
    1 int sourceRowIndex = (this.ItemsSource as IList).IndexOf(this.SelectedItem);
    2 int sourceColumnIndex = (e.OriginalSource as DataGridButton).ColumnIndex;
    3 
    4 int currentRowIndex = this.Items.IndexOf(this.SelectedItem);
    5 int currentColumnIndex = (this.View as GridView).Columns.IndexOf(this._DataGridColumns[sourceColumnIndex]);
    6 
    7 this.RaiseEvent(new DataGridEventArgs(ButtonClickEvent, sourceRowIndex, sourceColumnIndex, currentRowIndex, currentColumnIndex));
  這樣一來,我們就可以非常方便的在該控件的事件中直接使用SourceRowIndex、SourceColumnIndex、CurrentRowIndex、CurrentColumnIndex等的值了。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章