2

code snippetの背景色を簡単に変更する必要がありWPF DataGrid cellます。と がcolumn indexありrow indexます。中の色を変えたいCellEditEnding event hadler。私は書きevent handlerました。今、簡単にofcode snippetを変更する必要があります。background colorcell

4

1 に答える 1

1

次のようなものを使用すると、selected... を使用せずに特定のセルの背景を変更できます。

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>
于 2014-09-20T15:51:17.207 に答える