綜合應用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等的值了。
相關文章
相關標籤/搜索