您的位置:首页 > 职场人生

综合应用WPF/WCF/WF/LINQ之三十九:实现一个简单的DataGrid之获取某格的原始(或当前)行(或列)的Index

2008-02-23 22:00 951 查看
为什么这些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等的值了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  职场 DataGrid 休闲 Index
相关文章推荐