您的位置:首页 > 产品设计 > UI/UE

WPF备忘录(3)如何从 Datagrid 中获得单元格的内容与 使用值转换器进行绑定数据的转换IValueConverter

2013-07-24 08:09 866 查看
[b]一、如何从 Datagrid 中获得单元格的内容[/b]

   DataGrid 属于一种 ItemsControl, 因此,它有 Items 属性并且用ItemContainer 封装它的 items.

但是,WPF中的DataGrid 不同于Windows Forms中的 DataGridView。 在DataGrid的Items集合中,DataGridRow

是一个Item,但是,它里面的单元格却是被封装在 DataGridCellsPresenter 的容器中;因此,我们不能使用

DataGridView.Rows.Cells 这样的语句去获得单元格的内容。但是,在WPF中我们可以通过可视树(VisualTree)

去进入到控件“内部“, 那么,我们当然可以通过VisualTree进入DataGrid中的DataGridRowDataGridCellsPresenter

并且得到在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);
else
break;
}

return child;
}


[b] 二、WPF 使用值转换器进行绑定数据的转换IValueConverter[/b]

[b]    有的时候,我们想让绑定的数据以其他的格式显示出来,或者转换成其他的类型,我们可以[/b]

[b]使用值转换器来实现.[/b][b]比如我数据中保存了一个文件的路径”c:\abc\abc.exe”,但是我想让他在前台[/b]

[b]列表中显示为”abc.exe”.[/b][b]首先我们先建一个IvalueConverter接口的类.[/b]

[b]  [/b]

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}}"  />
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐