2013-12-18 3 views
1

У меня есть datagrid, который заполняется привязкой его к datatable.Измените цвет строки строки datagrid

Существует 100 строк.

Использование C# Как изменить цвет фона конкретной ячейки?

Скажем, например, 15-я строка, а цвет фона - зеленый.

DataGrid

<DataGrid Name="grid" ItemsSource="{Binding}" Height="300" Width="900" 
      AutoGenerateColumns="True" 
      VerticalScrollBarVisibility="Disabled" HorizontalAlignment="Center" VerticalAlignment="Top" RowHeight="40"> 
      <DataGrid.ItemsPanel> 
       <ItemsPanelTemplate> 
        <WrapPanel Orientation="Vertical" /> 
       </ItemsPanelTemplate> 
      </DataGrid.ItemsPanel> 
     </DataGrid> 
+2

удалить эту ужасную Нетипизированной, магию-струнный на основе 'DataTable' вещи и создать правильные, строго типизированные ViewModel для этого. Затем просто используйте «Style.Triggers» или подобное, чтобы изменить фон ячейки на основе значений из базовых данных. Не манипулируйте элементами пользовательского интерфейса в процедурный код в WPF. Для этого и предназначен XAML. –

ответ

0

На самом деле не существует никаких методов для доступа к отдельной строки в WPF DataGrid и у не должны это делать! Лучший способ заключается в использовании стиль сеттер

<Style TargetType="{x:Type DataGridCell}" x:Key="NumberCell">  
<Style.Setters> 
    <Setter Property="Background" Value="{Binding backgroundColor></Setter> 
</Style.Setters> 

Если вы не можете сделать это таким образом есть другой вариант: я нашел это решение в Интернете некоторое время назад, но может» Не помню, где.

Сначала нам нужны вспомогательные функции. Просто добавьте этот класс

namespace YOURNAMESPACE.DataGridHelpers 
/// <summary> 
/// Extension methods for DataGrid 
/// </summary> 
public static class DataGridHelper 
{ 
    /// <summary> 
    /// Gets the visual child of an element 
    /// </summary> 
    /// <typeparam name="T">Expected type</typeparam> 
    /// <param name="parent">The parent of the expected element</param> 
    /// <returns>A visual child</returns> 
    public static T GetVisualChild<T>(Visual parent) where T : Visual 
    { 
     T child = default(T); 
     int numVisuals = VisualTreeHelper.GetChildrenCount(parent); 
     for (int i = 0; i < numVisuals; i++) 
     { 
      Visual v = (Visual)VisualTreeHelper.GetChild(parent, i); 
      child = v as T; 
      if (child == null) 
      { 
       child = GetVisualChild<T>(v); 
      } 
      if (child != null) 
      { 
       break; 
      } 
     } 
     return child; 
    } 



    /// <summary> 
    /// Gets the specified cell of the DataGrid 
    /// </summary> 
    /// <param name="grid">The DataGrid instance</param> 
    /// <param name="row">The row of the cell</param> 
    /// <param name="column">The column index of the cell</param> 
    /// <returns>A cell of the DataGrid</returns> 
    public static DataGridCell GetCell(this DataGrid grid, DataGridRow row, int column) 
    { 
     if (row != null) 
     { 
      DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(row); 

      if (presenter == null) 
      { 
       grid.ScrollIntoView(row, grid.Columns[column]); 
       presenter = GetVisualChild<DataGridCellsPresenter>(row); 
      } 

      DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column); 

      return cell; 
     } 
     return null; 
    } 

    /// <summary> 
    /// Gets the specified cell of the DataGrid 
    /// </summary> 
    /// <param name="grid">The DataGrid instance</param> 
    /// <param name="row">The row index of the cell</param> 
    /// <param name="column">The column index of the cell</param> 
    /// <returns>A cell of the DataGrid</returns> 
    public static DataGridCell GetCell(this DataGrid grid, int row, int column) 
    { 
     DataGridRow rowContainer = grid.GetRow(row); 
     return grid.GetCell(rowContainer, column); 
    } 

    /// <summary> 
    /// Gets the specified row of the DataGrid 
    /// </summary> 
    /// <param name="grid">The DataGrid instance</param> 
    /// <param name="index">The index of the row</param> 
    /// <returns>A row of the DataGrid</returns> 
    public static DataGridRow GetRow(this DataGrid grid, int index) 
    { 
     DataGridRow row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromIndex(index); 
     if (row == null) 
     { 
      // May be virtualized, bring into view and try again. 
      grid.UpdateLayout(); 
      grid.ScrollIntoView(grid.Items[index]); 
      row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromIndex(index); 
     } 
     return row; 
    } 

    /// <summary> 
    /// Gets the selected row of the DataGrid 
    /// </summary> 
    /// <param name="grid">The DataGrid instance</param> 
    /// <returns></returns> 
    public static DataGridRow GetSelectedRow(this DataGrid grid) 
    { 
     return (DataGridRow)grid.ItemContainerGenerator.ContainerFromItem(grid.SelectedItem); 
    } 
} 

}

Теперь вы можете получить DataGrid колонке 0 строка 15 с:

var cell = dataGrid.GetCell(15, 0); 

и установите цвет на зеленый

cell.Background = Brushes.Green; 
0

Добавление обработчика к событию LoadingRowDataGrid следующим образом:

<DataGrid Name="grid" ItemsSource="{Binding}" Height="300" Width="900" 
      AutoGenerateColumns="True" VerticalAlignment="Top" RowHeight="40" 
      VerticalScrollBarVisibility="Disabled" HorizontalAlignment="Center" 
      LoadingRow="DataGrid_LoadingRow" > 
     <DataGrid.ItemsPanel> 
      <ItemsPanelTemplate> 
       <WrapPanel Orientation="Vertical" /> 
      </ItemsPanelTemplate> 
     </DataGrid.ItemsPanel> 
    </DataGrid> 

Затем в коде позади:

 int index = 0; 
    public void DataGrid_LoadingRow(object sender, DataGridRowEventArgs e) 
    { 
     var row = (DataRowView)e.Row.Item; 
     //If you want the content of a specific column of the current row 
     //var content = row.Row[0].ToString(); 
     if (index == 15) 
     { 
      e.Row.Background = new SolidColorBrush(Colors.DeepSkyBlue); 
      e.Row.Foreground = new SolidColorBrush(Colors.Black); 
     } 
     index ++ ; //don't forget to increase the index 
    } 
+0

Я получаю это: невозможно лить объект типа «MS.Internal.NamedObject» для ввода «System.Data.DataRowView» в var row = (DataRowView) e.Row.Item; – RSM

+0

Какую структуру вы используете? –

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