问题
I have a datagrid binded to an object collection.
One property of the objects is a string that store a color value.
On this "COLORBACKGROUND" cell click, a colorpicker opens to change it.
What I need is to change the background color of the cell by the value displayed in datagrid rows (#RGB).
<DataGrid SelectionUnit="Cell" SelectedCellsChanged="DgDataTable_OnSelectedCellsChanged" x:Name="DgDataTable" Grid.Row="0" Grid.ColumnSpan="2" Margin="10,20,10,0" AutoGenerateColumns="true" HeadersVisibility="All" RowHeaderWidth="20" Style="{StaticResource AzureDataGrid}" GridLinesVisibility="Horizontal" LoadingRow="dgDataTable_LoadingRow" ColumnHeaderHeight="10" AlternatingRowBackground="{DynamicResource {x:Static SystemColors.GradientActiveCaptionBrushKey}}" AutoGeneratingColumn="DgDataTable_AutoGeneratingColumn">
<DataGrid.RowHeaderStyle>
<Style TargetType="DataGridRowHeader">
<Setter Property="FontSize" Value="10"/>
<Setter Property="Background" Value="LightCyan"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
</Style>
</DataGrid.RowHeaderStyle>
<DataGrid.CellStyle>
<Style TargetType="DataGridCell">
<Setter Property="TextBlock.TextAlignment" Value="Center"/>
<!-- <Style.Triggers>
<Trigger Property="Text" Value="John">
<Setter Property="Background" Value="LightGreen"/>
</Trigger>
</Style.Triggers> -->
</Style>
</DataGrid.CellStyle>
</DataGrid>
I tried something with AutoGenerating column :
private void DgDataTable_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
if (e.PropertyName == "SrcAlert")
{
DataGridComboBoxColumn cb = new DataGridComboBoxColumn();
e.Column = cb;
cb.ItemsSource = new List<string> {"1", "2"};
cb.SelectedValueBinding = new Binding("SrcAlert");
e.Column.Header = "SrcAlert";
}
if (e.PropertyName.Equals("ColorBackground"))
{
DataGridTextColumn tc = new DataGridTextColumn();
e.Column = tc;
tc.Foreground = (Color)ColorConverter.ConvertFromString(DgDataTable.CurrentCell.Item.ColorBackground);
}
}
this Item.ColorBackground
doesn't compile... I put it for my explanation, thats what I need.
I tried another solution I found :
if (e.PropertyName.Equals("ColorBackground"))
{
string s = DgDataTable.CurrentCell.Item.ToString();
e.Column.CellStyle.Setters.Add(new Setter(DataGridCell.BackgroundProperty, (Color)ColorConverter.ConvertFromString(s)));
}
but that was a fail.
Thank you for your help !
Edit : A screenshot of ASh solution that works perfectly for me:
EDIT : I adapted your solution for multiple columns with color Picker :
I add style setters to display only colors in the cells :
<Style TargetType="DataGridCell" x:Key="ColorPickerCellBG"
BasedOn="{StaticResource CommonCell}">
<Setter Property="Background" Value="{Binding Path=BG}"/>
<Setter Property="Foreground" Value="Transparent"/>
<Setter Property="Width" Value="30"></Setter>
</Style>
<Style TargetType="DataGridCell" x:Key="ColorPickerCellAL"
BasedOn="{StaticResource CommonCell}">
<Setter Property="Background" Value="{Binding Path=AL}"/>
<Setter Property="Foreground" Value="Transparent"/>
<Setter Property="Width" Value="30"></Setter>
</Style>
<Style...
When the cell is clicked, the rgb color value is visible, the style must be "ClickedCell"... How can I Improve that ?
回答1:
it is possible to apply special style to a single auto-generated column.
declare two cell styles in resources
<Window.Resources>
<Style TargetType="DataGridCell" x:Key="CommonCell"
BasedOn="{StaticResource {x:Type DataGridCell}}">
<Setter Property="TextBlock.TextAlignment" Value="Center"/>
</Style>
<Style TargetType="DataGridCell" x:Key="ColorPickerCell"
BasedOn="{StaticResource CommonCell}">
<Setter Property="Background" Value="{Binding Path=ColorBackground}"/>
</Style>
</Window.Resources>
ColorPickerCell
inherits CommonCell
style.
<DataGrid SelectionUnit="Cell"
x:Name="DgDataTable"
AutoGenerateColumns="true" HeadersVisibility="All" RowHeaderWidth="20"
GridLinesVisibility="Horizontal"
ColumnHeaderHeight="10"
AlternatingRowBackground="{DynamicResource {x:Static SystemColors.GradientActiveCaptionBrushKey}}"
CellStyle="{StaticResource CommonCell}"
AutoGeneratingColumn="DgDataTable_AutoGeneratingColumn">
<DataGrid.RowHeaderStyle>
<Style TargetType="DataGridRowHeader">
<Setter Property="FontSize" Value="10"/>
<Setter Property="Background" Value="LightCyan"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
</Style>
</DataGrid.RowHeaderStyle>
</DataGrid>
change CellStyle
for a generated column:
private void DgDataTable_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
if (e.PropertyName == "ColorBackground")
{
e.Column.CellStyle = (sender as DataGrid).FindResource("ColorPickerCell") as Style;
}
}
回答2:
Apply a Converter
, this Converter
is used for two diff. purpose hence returns two diff types. Beauty of this approach is : You can change the property
in XAML
itself. No change needed in code now, and hence it is MVVM friendly.
For example, in DataTrigger
change Value=BkgProp
to Value=Name
and see.
Sample XAML :
<Window ...>
<Window.Resources>
<local:PropBasedStringToColorConverter x:Key="StringToColorCnvKey"/>
</Window.Resources>
<Grid>
<DataGrid x:Name="Dgrd">
<DataGrid.Resources>
<Style TargetType="DataGridCell">
<Style.Triggers>
<DataTrigger Binding="{Binding .Column, RelativeSource={RelativeSource Self}, Converter={StaticResource StringToColorCnvKey}}" Value="BkgProp">
<Setter Property="Background" Value="{Binding BkgProp, Converter={StaticResource StringToColorCnvKey}}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.Resources>
</DataGrid>
</Grid>
</Window>
Sample Data :
Dgrd.ItemsSource = new[] { new { BkgProp = "#abcdef", Name = "Anjum" }, new { BkgProp = "#edf2ed", Name = "Anjum" }, new { BkgProp = "#ff0000", Name = "Anjum" } }.ToList();
Converter Code :
public class PropBasedStringToColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
object result = null;
if (value == null) return "N/A";
if (value.GetType() == typeof(DataGridTextColumn))
{
string path = ((Binding)((DataGridTextColumn)value).Binding).Path.Path;
return path;
}
else if (value.GetType() == typeof(string))
{
result = new SolidColorBrush((Color)ColorConverter.ConvertFromString(value.ToString()));
}
return result;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
来源:https://stackoverflow.com/questions/38348529/how-to-change-background-color-for-some-cell-in-wpf-datagrid