文章出處

一、如何從 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);
    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}}"  />

 

 


文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()