2011-07-31 182 views
0

是否有可能獲得單元格索引,其中列標題=「column4」和行包含「232」 例如,我上傳的屏幕截圖是否有可能獲得紅色單元格索引並使其變爲紅色?如果wpf數據網格有那個函數做wpf工具包數據網格有?列和行從代碼通過Style/TriggerBinding與轉換器將後面enter image description heredatagrid獲取單元格索引

回答

7

你應該做這個喜歡

<DataGrid Name="dataGrid" 
      ...> 
    <DataGrid.Columns> 
     <DataGridTextColumn Header="column4" Binding="{Binding column4}"> 
      <DataGridTextColumn.CellStyle> 
       <Style TargetType="DataGridCell"> 
        <Style.Triggers> 
         <DataTrigger Binding="{Binding column4}" Value="232"> 
          <Setter Property="Background" Value="Red"/> 
         </DataTrigger> 
        </Style.Triggers> 
       </Style> 
      </DataGridTextColumn.CellStyle> 
     </DataGridTextColumn> 
     <!--...--> 
    </DataGrid.Columns> 
    <!--...--> 
</DataGrid> 

默認情況下,DataGrid如此只有DataGridRows使用虛擬化目前用戶可見的數據將被加載。其他行將被創建,一旦它們變得可見,所以如果你想在後面的代碼中設置一些單元格的樣式可能會變得非常混亂(你試圖訪問的單元格可能還不存在)。

要得到DataGridCell索引行/列,您可以定義一個輔助類(DataGridHelper),並使用它像這樣

DataGridCell cell = DataGridHelper.GetCell(dataGrid, 0, 2); 
if (cell != null) 
{ 
    cell.Background = Brushes.Red; 
} 

DataGridHelper

static class DataGridHelper 
{ 
    static public DataGridCell GetCell(DataGrid dg, int row, int column) 
    { 
     DataGridRow rowContainer = GetRow(dg, row); 

     if (rowContainer != null) 
     { 
      DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer); 

      // try to get the cell but it may possibly be virtualized 
      DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column); 
      if (cell == null) 
      { 
       // now try to bring into view and retreive the cell 
       dg.ScrollIntoView(rowContainer, dg.Columns[column]); 
       cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column); 
      } 
      return cell; 
     } 
     return null; 
    } 

    static public DataGridRow GetRow(DataGrid dg, int index) 
    { 
     DataGridRow row = (DataGridRow)dg.ItemContainerGenerator.ContainerFromIndex(index); 
     if (row == null) 
     { 
      // may be virtualized, bring into view and try again 
      dg.ScrollIntoView(dg.Items[index]); 
      row = (DataGridRow)dg.ItemContainerGenerator.ContainerFromIndex(index); 
     } 
     return row; 
    } 

    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); 
      } 
      if (child != null) 
      { 
       break; 
      } 
     } 
     return child; 
    } 
} 
相關問題