WPF学习备忘(3) Datagrid中的数据处理2013-11-26 cnblogs 幕三少如何从 Datagrid 中获得单元格的内容与 使用值转换器进行绑定数据的转换IValueConverter一、如何从 Datagrid 中获得单元格的内容DataGrid 属于一种 ItemsControl, 因此,它有 Items 属性并且用ItemContainer 封装它的 items.但是,WPF中的DataGrid 不同于Windows Forms中 的 DataGridView。 在DataGrid的Items集合中,DataGridRow是一个Item,但是,它里面的单元格却是被封装 在 DataGridCellsPresenter 的容器中;因此,我们不能使用像DataGridView.Rows.Cells 这样的语句去获得 单元格的内容。但是,在WPF中我们可以通过可视树(VisualTree)去进入到控件“内部“, 那么,我们当然 可以通过VisualTree进入DataGrid中的DataGridRow 和 DataGridCellsPresenter,并且得到在 DataGridCellsPresenter中的实例, 大家可以通过以下的代码遍历VisualTree
DataGridRow rowContainer = (DataGridRow)dataGrid1.ItemContainerGenerator.ContainerFromIndex(rowIndex);DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer);DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex); // ... public static T GetVisualChild<T>(Visual parent) where T : Visual{T child = default(T);int numVisuals = VisualTreeHelper.GetChildrenCount(parent); for (int i = 0; i < numVisuals; i++){Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);child = v as T; if (child == null)child = GetVisualChild<T>(v);elsebreak;} return child;}
二、WPF 使用值转换器进行绑定数据的转换IValueConverter有的时候,我们想让绑定的数 据以其他的格式显示出来,或者转换成其他的类型,我们可以使用值转换器来实现.比如我数据中保存了一个文 件的路径”c:abcabc.exe”,但是我想让他在前台列表中显示为”abc.exe”.首先我们先建一个 IvalueConverter接口的类.
class GetFileName : IValueConverter{//Convert方法用来将数据转换成我们想要的显示的格式public object Convert(object value, Type targetType, object parameter, CultureInfo culture){FileInfo fi = new FileInfo((string)value);return fi.Name;}//ConvertBack方法将显示值转换成原来的格式,因为我不需要反向转换,所以直接抛出个异常public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture){throw new NotImplementedException();}}
为了使用这个转换器,我们要将项目的名称空间映射到xaml中,比如我项目名字为自动更新,用local 作为空间名称前缀xmlns:local="clr-namespace:命名空间"为了使用的更方便,我 们在Resources集合中创建一个转换器对象
<Window.Resources><local:GetFileName x:Key="GetFileName"></local:GetFileName></Window.Resources>
现在我们去绑定数据的地方使用StaticResource来指向转换器
<TextBlock><TextBlock.Text><Binding Path="FileName"><Binding.Converter><local:GetFileName></local:GetFileName></Binding.Converter></Binding></TextBlock.Text></TextBlock>
或者这样使用:
<TextBlock Text="{Binding Path=FileName,Converter={StaticResource GetFileName}}"/>