![](/img/trans.png)
[英]Change WPF DataGrid cell Background color on CellEditEnding
[英]Change Background color of cell in WPF DataGrid
我需要一個簡單的code snippet
來更改WPF
DataGrid
cell
的背景顏色。 我有column index
和row index
。 我想在CellEditEnding
event hadler
內更改顏色。 我寫了event handler
。 現在我需要簡單的code snippet
來更改cell
的background color
。
類似下面的內容將允許您更改特定的單元格背景而無需使用選定的...
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
namespace SelectDataGridCell
{
public partial class MainWindow : Window
{
public MainWindow()
{
this.InitializeComponent();
}
private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
{
DataGridCell cell = GetCell(1, 1, myDataGrid);
cell.Background = new SolidColorBrush(Colors.Red);
}
public DataGridCell GetCell(int rowIndex, int columnIndex, DataGrid dg)
{
DataGridRow row = dg.ItemContainerGenerator.ContainerFromIndex(rowIndex) as DataGridRow;
DataGridCellsPresenter p = GetVisualChild<DataGridCellsPresenter>(row);
DataGridCell cell = p.ItemContainerGenerator.ContainerFromIndex(columnIndex) as DataGridCell;
return cell;
}
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;
}
}
}
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
x:Class="SelectDataGridCell.MainWindow"
x:Name="Window"
Title="MainWindow"
Width="640" Height="480">
<Grid x:Name="LayoutRoot" DataContext="{Binding Source={StaticResource SampleDataSource}}">
<DataGrid x:Name="myDataGrid" Margin="0,0,244,205" AutoGenerateColumns="False" ItemsSource="{Binding Collection}">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Property1}" Header="Property1"/>
<DataGridCheckBoxColumn Binding="{Binding Property2}" Header="Property2"/>
</DataGrid.Columns>
</DataGrid>
<Button Content="Button" HorizontalAlignment="Left" VerticalAlignment="Bottom" Width="75" Margin="8,0,0,146.04" Click="Button_Click"/>
</Grid>
</Window>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.