2
我需要一個簡單的code snippet
來更改背景顏色WPF
DataGrid
cell
。我有column index
和row index
。我想改變CellEditEnding
event hadler
中的顏色。我寫了event handler
。現在我需要簡單的code snippet
來更改的background color
。更改WPF DataGrid中單元格的背景顏色
我需要一個簡單的code snippet
來更改背景顏色WPF
DataGrid
cell
。我有column index
和row index
。我想改變CellEditEnding
event hadler
中的顏色。我寫了event handler
。現在我需要簡單的code snippet
來更改的background color
。更改WPF DataGrid中單元格的背景顏色
像下面這樣將允許您更改特定單元格的背景未經允許使用選擇具有...
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
namespace SelectDataGridCell
{
\t public partial class MainWindow : Window
\t {
\t \t public MainWindow()
\t \t {
\t \t \t this.InitializeComponent();
\t \t }
\t \t private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
\t \t {
\t \t \t DataGridCell cell = GetCell(1, 1, myDataGrid);
\t \t cell.Background = new SolidColorBrush(Colors.Red);
\t \t }
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;
}
\t }
}
<Window
\t xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
\t xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
\t x:Class="SelectDataGridCell.MainWindow"
\t x:Name="Window"
\t Title="MainWindow"
\t Width="640" Height="480">
\t <Grid x:Name="LayoutRoot" DataContext="{Binding Source={StaticResource SampleDataSource}}">
\t \t <DataGrid x:Name="myDataGrid" Margin="0,0,244,205" AutoGenerateColumns="False" ItemsSource="{Binding Collection}">
\t \t \t <DataGrid.Columns>
\t \t \t \t <DataGridTextColumn Binding="{Binding Property1}" Header="Property1"/>
\t \t \t \t <DataGridCheckBoxColumn Binding="{Binding Property2}" Header="Property2"/>
\t \t \t </DataGrid.Columns>
\t \t </DataGrid>
\t \t <Button Content="Button" HorizontalAlignment="Left" VerticalAlignment="Bottom" Width="75" Margin="8,0,0,146.04" Click="Button_Click"/>
\t </Grid>
</Window>