【问题标题】:Set Background of Particular DataGrid Cell设置特定 DataGrid 单元格的背景
【发布时间】:2012-03-07 02:29:30
【问题描述】:

我希望设置特定单元格的背景颜色。该行在后面的代码中被选中。尽管在代码中使用 dataGrid 的 CurrentCell 属性选择了单元格,但 IsSelected 属性似乎不起作用。只在形式上起作用。

XAML:

 <Style x:Key="CellStyle" TargetType="{x:Type dg:DataGridCell}">  
        <Style.Triggers> 
            <Trigger Property="IsSelected" Value="True">  
                <Setter Property="Background" Value="Yellow" /> 
            </Trigger> 
        </Style.Triggers> 
    </Style> 

代码:

dg.CurrentCell = new DataGridCellInfo(dg.Items[0],dg.Columns[0]);

dg.CellStyle = this.FindResource("CellStyle") as Style;

【问题讨论】:

  • 您是否尝试过为 IsSelected 属性使用 EventTrigger?
  • 您的 FindResource 调用结果是 Style 还是 null?

标签: c# wpf datagrid


【解决方案1】:

试试这个:

可以在xaml中设置单元格样式:

<DataGrid CellStyle="{StaticResource CellStyle}"

然后:

   var dataGridCellInfo = new DataGridCellInfo(dataGrid.Items[0], dataGrid.Columns[0]);
   dataGrid.SelectedCells.Clear();
   dataGrid.SelectedCells.Add(dataGridCellInfo);

【讨论】:

  • 谢谢,这行得通。一旦失去焦点,是否可以让它突出显示单元格?
  • nvm... 注释掉 Clear... 谢谢!
【解决方案2】:

试试这个示例代码,它对我有用

public Window8() {
  this.InitializeComponent();

  this.Loaded += (sender, args) =>
                    {
                      var cellStyle = this.FindResource("CellStyle") as Style;
                      this.dg.CellStyle = cellStyle;
                      this.dg.SelectedIndex = 0;
                    };
}

<Window.Resources>
  <Style x:Key="CellStyle"
          TargetType="{x:Type DataGridCell}">
    <Style.Triggers>
      <Trigger Property="IsSelected"
                Value="True">
        <Setter Property="Background"
                Value="Yellow" />
        <Setter Property="Foreground"
                Value="Black" />
      </Trigger>
    </Style.Triggers>
  </Style>

</Window.Resources>

注意

样式应用于所有单元格!

希望对你有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-27
    • 2011-12-12
    • 2011-04-29
    • 2022-01-23
    • 2013-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多