2016-07-13 4 views
1

У меня есть datagrid, привязанный к коллекции объектов.Как изменить цвет фона для некоторой ячейки в WPF DataGrid?

Одно свойство объектов - это строка, в которой хранится значение цвета.

my dataGrid

На этой "COLORBACKGROUND" клетки мыши, ColorPicker открывается, чтобы изменить его.

Мне нужно изменить цвет фона ячейки на значение, отображаемое в строках datagrid (#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> 

Я пытался что-то с колонкой Автогенераторной:

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); 
    } 
} 

это Item.ColorBackground не компилируется ... Я положил его на мое объяснение, вот что мне нужно.

Я попробовал другое решение, которое я нашел:

if (e.PropertyName.Equals("ColorBackground")) 
{ 
    string s = DgDataTable.CurrentCell.Item.ToString(); 
    e.Column.CellStyle.Setters.Add(new Setter(DataGridCell.BackgroundProperty, (Color)ColorConverter.ConvertFromString(s))); 
} 

, но это был провал.

Благодарим за помощь!


Edit: Скриншот решения АШ, который отлично работает для меня:

enter image description here


EDIT: Я приспособил свое решение для нескольких столбцов с выбором цвета:

enter image description here

Я добавляю стилизаторы для отображения только цветов в клетках:

<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... 

Когда клетка нажата, значение цвета RGB видно, стиль должен быть «ClickedCell» ... Как я могу улучшить это?

+0

что смысл <Что мне нужно изменить цвет фона ячейку по значению, отображаемому в строках datagrid (#RGB). > – AnjumSKhan

+0

Вместо того, чтобы отображать «# 556677» в ячейке, мне бы хотелось, чтобы это был цвет фона. – Alexus

ответ

3

можно применить специальный стиль к одному автогенерированному столбцу.

объявить два стиля ячейки в ресурсах

<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 наследует CommonCell стиль.

<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> 

изменения CellStyle для генерируемого столбца:

private void DgDataTable_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e) 
{ 
    if (e.PropertyName == "ColorBackground") 
    { 
     e.Column.CellStyle = (sender as DataGrid).FindResource("ColorPickerCell") as Style; 
    } 
} 
+0

Да! Простое и элегантное решение ASh. Спасибо. – Alexus

+0

Я отредактирую свое сообщение, чтобы показать свое решение. – Alexus

1

Нанести Converter, этот Converter используется для двух дифференциала. поэтому возвращает два типа diff. Красота такого подхода: вы можете изменить property в XAML. В коде нет изменений, и, следовательно, это MVVM.

Например, в DataTrigger изменить Value=BkgProp на Value=Name и посмотреть.

Пример 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> 

Образец данных:

Dgrd.ItemsSource = new[] { new { BkgProp = "#abcdef", Name = "Anjum" }, new { BkgProp = "#edf2ed", Name = "Anjum" }, new { BkgProp = "#ff0000", Name = "Anjum" } }.ToList(); 

конвертер Код:

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(); 
    } 
} 
+0

Спасибо за ваш ответ AnjumSKhan. – Alexus

+0

Я забыл проверить конкретную колонку, извините! – AnjumSKhan

+0

ОК, я тоже попробую ваше решение – Alexus

Смежные вопросы