首页 文章

设置特定DataGrid单元格的背景

提问于
浏览
0

我希望设置特定单元格的背景颜色 . 该行在后面的代码中被选中 . 虽然使用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;

2 回答

  • 0

    试试这个:

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

    <DataGrid CellStyle="{StaticResource CellStyle}"
    

    然后:

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

    尝试这个示例代码,它适用于我

    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>
    

    NOTE

    风格适用于所有细胞!

    希望这可以帮助

相关问题