首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >更改数据网格单元格的背景

更改数据网格单元格的背景
EN

Stack Overflow用户
提问于 2012-01-06 22:46:36
回答 3查看 1.6K关注 0票数 0

我可以通过下面的C#代码来改变数据单元的背景-

代码语言:javascript
运行
复制
    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触发器/或任何其他方法来提高网格的性能。

EN

回答 3

Stack Overflow用户

发布于 2012-01-06 23:49:14

由于需要两个动态值来确定单元格的背景颜色(ColumnIndexValuesList),因此需要使用接受这两个值并返回一种颜色的MultiConverter

例如,

代码语言:javascript
运行
复制
if ValueList[ColumnIndex].IsBlank)
    Return Colors.Red; // Might be Brushes.Red too, can't remember
else
    Return Colors.White;

然后,可以将触发器隐式应用于样式未指定键的所有DataGridCells

代码语言:javascript
运行
复制
<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>

我可能在MultiBindingColumn.DisplayIndex绑定中使用了错误的RelativeSource语法,但是绑定应该指向Self,即DataGridCell

票数 3
EN

Stack Overflow用户

发布于 2012-01-06 23:03:33

欢迎来到WPF世界;)

你可以试试这个:

代码语言:javascript
运行
复制
<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>

干杯,

Sebi

票数 0
EN

Stack Overflow用户

发布于 2012-01-06 23:14:06

我认为你不能,因为数据网格只定义了结构,而不是样式。

我在网格单元格中使用矩形。

代码语言:javascript
运行
复制
    <Rectangle Grid.Column="1" Grid.Row="1" Fill="Red"></Rectangle>
    <TextBox Grid.Column="1" Grid.Row="1" Background="Transparent" Text="test"></TextBox>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8759584

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档