DataGrid получить индекс клетки - PullRequest
1 голос
/ 31 июля 2011

Можно ли получить индекс ячейки, где header header = "column4", а строка содержит "232", например, если я загрузил снимок экрана, можно ли получить индекс красной ячейки и чем сделать его красным?и если wpf datagrid имеет эту функцию, то есть ли у сетки данных wpf toolkit?столбцы и строки добавляются из кода за enter image description here

1 Ответ

8 голосов
/ 31 июля 2011

Вы должны сделать это через Style / Trigger или Binding с конвертером типа

<DataGrid Name="dataGrid"
          ...>
    <DataGrid.Columns>
        <DataGridTextColumn Header="column4" Binding="{Binding column4}">
            <DataGridTextColumn.CellStyle>
                <Style TargetType="DataGridCell">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding column4}" Value="232">
                            <Setter Property="Background" Value="Red"/>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </DataGridTextColumn.CellStyle>
        </DataGridTextColumn>
        <!--...-->
    </DataGrid.Columns>
    <!--...-->
</DataGrid>

По умолчанию DataGrid использует виртуализацию, поэтому будут загружены только те DataGridRows, которые видны пользователю в данный момент. Другие строки будут созданы после того, как они станут видимыми, поэтому, если вы попытаетесь стилизовать некоторые ячейки в коде, он может стать довольно грязным (ячейка, к которой вы пытаетесь получить доступ, может даже не существовать.)

Чтобы получить DataGridCell в строке / столбце индекса, вы можете определить вспомогательный класс (DataGridHelper) и использовать его следующим образом:

DataGridCell cell = DataGridHelper.GetCell(dataGrid, 0, 2);
if (cell != null)
{
    cell.Background = Brushes.Red;
}

DataGridHelper

static class DataGridHelper
{
    static public DataGridCell GetCell(DataGrid dg, int row, int column)
    {
        DataGridRow rowContainer = GetRow(dg, row);

        if (rowContainer != null)
        {
            DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer);

            // try to get the cell but it may possibly be virtualized
            DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
            if (cell == null)
            {
                // now try to bring into view and retreive the cell
                dg.ScrollIntoView(rowContainer, dg.Columns[column]);
                cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
            }
            return cell;
        }
        return null;
    }

    static public DataGridRow GetRow(DataGrid dg, int index)
    {
        DataGridRow row = (DataGridRow)dg.ItemContainerGenerator.ContainerFromIndex(index);
        if (row == null)
        {
            // may be virtualized, bring into view and try again
            dg.ScrollIntoView(dg.Items[index]);
            row = (DataGridRow)dg.ItemContainerGenerator.ContainerFromIndex(index);
        }
        return row;
    }

    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;
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...