2012-01-06 93 views
0

的背景下,我能夠通過下面的C#代碼改變DATACELL的背景 -改變DataGrid單元格

private void Retrieve_rows(object item) 
    { 
     DataRow row = mygrid.GetContainerFromItem(item) as DataGrid.DataRow; 

     if (row != null) 
     { 
      SolidColorBrush redColor = new SolidColorBrush (Colors.Red); 

      foreach (DataGrid.DataCell cell in row.Cells) 
      { 
       var dc = ((System.Windows.FrameworkElement)(((DataGrid.Cell)(cell)).ParentRow)).DataContext; 

       // get my custom object and change color if IsBlank value is set to true 
       MyRowObject rowObject = dc as MyRowObject; 

       for (int counter = 0; counter < rowObject.values.Count; counter++) 
       { 
         if (rowObject.values[counter].IsBlank == true) 
          row.Cells[counter].Background = redColor; 
        } 
       } 
       return; 
      } 
     } 
    } 

但有了這個代碼,應用程序性能下降在很大程度上。有沒有辦法將上面的代碼轉換爲XAML觸發器/或其他方式來提高網格的性能。

回答

0

歡迎WPF世界;)

你可以試試這個:

<DataGrid Name="myGrid"> 
    <DataGrid.Columns> 
    <DataGridTextColumn Header="Col1" Binding="{Binding Col1}" /> 
    <DataGridTextColumn Header="Col2" Binding="{Binding Col2}" /> 
    </DataGrid.Columns> 
<DataGrid.CellStyle> 
    <Style TargetType="{x:Type DataGridCell}"> 
    <Setter Property="Background" Value="Red" /> 
    </Style> 
    </DataGrid.CellStyle> 
</DataGrid> 

乾杯,

塞比

+0

嗨,謝謝,謝謝你的回覆。但我已經嘗試過下面的xaml代碼,這是行不通的。 user1134489 2012-01-06 15:09:11

+1

請更具體一點 - 您打算如何處理這個多數據觸發器?這似乎有點偏題... – 2012-01-06 15:14:18

0

我認爲你不能因爲DataGrid中只定義結構不是風格。
我在網格單元格中使用矩形。

<Rectangle Grid.Column="1" Grid.Row="1" Fill="Red"></Rectangle> 
    <TextBox Grid.Column="1" Grid.Row="1" Background="Transparent" Text="test"></TextBox> 
3

由於需要兩個動態值來確定電池(ColumnIndexValuesList)的背景顏色,你需要使用一個MultiConverter它接受這兩個值,並返回一個顏色。

例如,

if ValueList[ColumnIndex].IsBlank) 
    Return Colors.Red; // Might be Brushes.Red too, can't remember 
else 
    Return Colors.White; 

的觸發然後可以隱含適用於所有DataGridCells與沒有鑰匙的樣式指定

<Style TargetType="{x:Type DataGridCell}"> 
    <Setter Property="Background"> 
     <Setter.Value> 
      <MultiBinding Converter="{StaticResource MyMultiConverter}"> 
       <Binding Path="Column.DisplayIndex" RelativeSource="{RelativeSource Self}" /> 
       <Binding Path="ValueList" /> 
      </MultiBinding> 
     </Setter.Value> 
    </Setter> 
</Style> 

我可能具有RelativeSource語法錯誤的Column.DisplayIndex綁定的MultiBinding,但綁定應該指向Self,這是DataGridCell