2012-01-06 92 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