为什么这些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等的值了。