WPF数据表格:当文本改变时改变颜色

3

当用户更改单元格的文本或内容时,我希望能够更改DataGrid中该单元格的颜色。

我正在使用WPF和C#。

我有一个简单的DataGrid:

<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文件中尝试改变单元格,但失败了。
我需要一个在内容更改时会被触发的事件。

你目前尝试了什么?展示一些代码。查看metaSO问题Jon Skeet: Coding Blog,了解如何编写和提出好问题的建议。 - Yaroslav
请在问题中添加您的代码,而不是作为评论。使用问题下方标签列表左下角的“编辑”链接。 - Yaroslav
2个回答

0

已解决:

 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>


0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接