如何從 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);
else
break;
}
return child;
}
二、WPF 使用值轉換器進行綁定數據的轉換IValueConverter
有的時候,我們想讓綁定的數 據以其他的格式顯示出來,或者轉換成其他的類型,我們可以使用值轉換器來實現.比如我數據中保存了一個文 件的路徑”c:\abc\abc.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}}" />