日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

如何从 Datagrid 中获得单元格的内容与 使用值转换器进行绑定数据的转换IValueConverter...

發布時間:2023/12/1 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 如何从 Datagrid 中获得单元格的内容与 使用值转换器进行绑定数据的转换IValueConverter... 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

一、如何從 Datagrid 中獲得單元格的內容

   DataGrid?屬于一種?ItemsControl,?因此,它有?Items?屬性并且用ItemContainer?封裝它的?items.?

但是,WPF中的DataGrid?不同于Windows Forms中的?DataGridView。?在DataGridItems集合中,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:\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}}" />

轉載于:https://www.cnblogs.com/jameslif/p/3209955.html

總結

以上是生活随笔為你收集整理的如何从 Datagrid 中获得单元格的内容与 使用值转换器进行绑定数据的转换IValueConverter...的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。