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