Datagrid foreground colour not working

不想你离开。 提交于 2019-12-20 07:17:09

问题


I have a simple datagrid that display bidimensional data. I have tried it in a test project and the result is nice.

Here is the xmal:

<Grid >
<DataGrid Name="dg" Margin="50" FontSize="26" CellEditEnding="dg_CellEditEnding" BeginningEdit="dg_BeginningEdit"  LoadingRow="DataGrid_LoadingRow" EnableRowVirtualization="False"  AutoGeneratingColumn="dg_AutoGeneratingColumn"/>
</Grid>

and the relevant event code:

 private void DataGrid_LoadingRow(object sender, System.Windows.Controls.DataGridRowEventArgs e)
{
  e.Row.Header = "R" + ((e.Row.GetIndex()) + 1).ToString();
}

private void dg_AutoGeneratingColumn(object sender, System.Windows.Controls.DataGridAutoGeneratingColumnEventArgs e)
{
  string str = e.PropertyName;
  int num = int.Parse(e.PropertyName);
  e.Column.Header = "C" + (num + 1).ToString();

}

then I have to put it in my real project which is a styled window.

So I put the same very easy xaml (adding background and foreground fore here I have a gradient background) so that the xamls is:

<Grid >
<DataGrid Name="dtgNests" Margin="50" FontSize="26" Background="White" Foreground="Black" HeadersVisibility="All" CellEditEnding=" dg_CellEditEnding" BeginningEdit="dg_BeginningEdit"  LoadingRow="DataGrid_LoadingRow" EnableRowVirtualization="False"  AutoGeneratingColumn="dg_AutoGeneratingColumn"/>
</Grid>

and the effect is:

so in short the FOREGROUND is not being set in any part. That is:

  • cells
  • row headers
  • column headers

so nowhere. Can anyone tell me why? thank you in advance Patrick


回答1:


In a WPF DataGrid, all cell-related design needs to be set as the Column's ElementStyle, which overrides the foreground set in your Grid. Try the following:

In your XAML resources:

<Style x:Key="BlackCellStyle" TargetType="{x:Type TextBlock}">
    <Setter Property="Foreground" Value="Black" />
</Style>

In your AutoGeneratingColumn handler:

private void dg_AutoGeneratingColumn(object sender, System.Windows.Controls.DataGridAutoGeneratingColumnEventArgs e)
{
  string str = e.PropertyName;
  int num = int.Parse(e.PropertyName);
  e.Column.Header = "C" + (num + 1).ToString();
  e.Column.ElementStyle = FindResource("BlackCellStyle") as Style;
}

This will apply the foreground directly to your cells



来源:https://stackoverflow.com/questions/35060738/datagrid-foreground-colour-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!