【问题标题】:WPF datagrid change color when text change文本更改时WPF数据网格更改颜色
【发布时间】:2012-10-26 10:48:52
【问题描述】:

当用户更改单元格的文本或内容时,我想更改数据网格中单元格的颜色。

我正在使用 WPF 和 C#。

我有一个简单的数据网格:

<DataGrid x:Name="dataGrid1" Grid.RowSpan="2" Margin="5" ItemsSource="{Binding Source=Horreos}" KeyDown="dataGrid1_KeyDown" SelectedCellsChanged="dataGrid1_SelectedCellsChanged"> <DataGrid.Columns > </DataGrid.Columns> </DataGrid> 

此事件:keydown 和 selectedcellschange 是更改我的颜色单元格的测试。在 .cs 中,我尝试更改 cel....但失败了。

我需要一个在内容变化时发布的事件

【问题讨论】:

  • 到目前为止你尝试过什么?显示一些代码。查看metaSO questionJon Skeet: Coding Blog,了解如何写作并提出一个好问题。
  • 在问题上添加您的代码,而不是作为评论。使用问题左下角标签列表下方的 edit 链接。

标签: c# wpf datagrid colors


【解决方案1】:

设置一个行为,最简单的方法是使用 Blend。我在我的博客文章中提供了一个针对数据网格的示例:Xaml: Adding Visibility Behaviors Using Blend to A DataGrid for WPF or Silverlight

【讨论】:

    【解决方案2】:

    已解决:

     private void dataGrid1_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
        {
            DataGridCell gridCell = null;
            try
            {
                gridCell = GetCell(dataGrid1.SelectedCells[0]);
            }
            catch (Exception)
            {
            }
            if (gridCell != null)
                gridCell.Background = Brushes.Red;
    
        }
    public  DataGridCell GetCell(DataGridCellInfo dataGridCellInfo)
        {
            if (!dataGridCellInfo.IsValid)
            {
                return null;
            }
    
            var cellContent = dataGridCellInfo.Column.GetCellContent(dataGridCellInfo.Item);
            if (cellContent != null)
            {
                return (DataGridCell)cellContent.Parent;
            }
            else
            {
                return null;
            }
        }
    
    private void MyDataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            DataGrid grid = sender as DataGrid;
            e.Row.MouseEnter += (s, args) => Row_MouseEnter(s, grid);
            e.Row.MouseLeave += (s, args) => Row_MouseLeave(s, grid);
        }
    
        void Row_MouseLeave(object sender, DataGrid grid)
        {
            DataGridRow row = sender as DataGridRow;
            grid.SelectedIndex = -1;
        }
    
        void Row_MouseEnter(object sender, DataGrid grid)
        {
            DataGridRow row = sender as DataGridRow;
            grid.SelectedIndex = row.GetIndex();
    
        }
    

    当用户完成编辑时,单元格变为红色。

     <DataGrid x:Name="dataGrid1" Grid.RowSpan="2" SelectionUnit="CellOrRowHeader" 
                         Margin="5" ItemsSource="{Binding Source=Source}" LoadingRow="MyDataGrid_LoadingRow"  CellEditEnding="dataGrid1_CellEditEnding">
                <DataGrid.Columns>
    

    【讨论】:

      猜你喜欢
      • 2012-04-20
      • 1970-01-01
      • 2018-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-11
      • 2013-10-09
      相关资源
      最近更新 更多