Looping Through WPF DataGrid Using foreach

 ̄綄美尐妖づ 提交于 2020-01-02 03:32:05

问题


All, I am attempting to loop through a WPF DataGrid using a for each loop to change the background colour of erroneous cells. I have checked many questions but I have yet to find a sufficient answer. What I have so far is

public void RunChecks()
{
    const int baseColumnCount = 3;
    foreach (DataRowView rv in dataGrid.Items)
    {
        for (int i = baseColumnCount; i < dataGrid.Columns.Count; i++)
        {
            if (!CheckForBalancedParentheses(rv.Row[i].ToString()))
            {
                Color color = (Color)ColorConverter.ConvertFromString("#FF0000");
                row.Background = new SolidColorBrush(color); // Problem!
            }
        }
    }
}

The problem is that in order to change the Background colour of a row in my DataGrid I need to work with the DataGridRow object ascociated with the DataRowView rv.

How do I get a reference to the DataGridRow from the object rv (DataRowView)?

Thanks for your time.

Edit. Based upon the advice below I now have the following style which works with the mouse over event and set the back and fore font of the relevant cell. However, I am really lost as to how to apply the backcolor to a cell at run-time in my code above. The XML style is

<Window.Resources>
    <Style TargetType="{x:Type DataGridRow}">
        <Style.Triggers>
            <Trigger Property="IsMouseOver"
                     Value="True">
                <Setter Property="Background" Value="Red" />
                <Setter Property="FontWeight" Value="ExtraBold" />
            </Trigger>
        </Style.Triggers>
    </Style>
</Window.Resources>

回答1:


When you're working with WPF, avoid always accessing UI artifacts directly.

Create in you ModelView a property Color, and bind it to the background color of a single row template of your DataGrid view.

So in order to change the color you will loop throw the ModelView collecton and set/read Color property of every single object binded to every single row. By changing it, if binding is correctly settuped, you will affect row UI color appearance.

For concrete sample you can look on:

How do I bind the background of a data grid row to specific color?




回答2:


You can use the ItemContainerGenerator to get the visual representation for your data i.e. DataGridRow -

DataGridRow row = (DataGridRow)dataGrid.ItemContainerGenerator
                                       .ContainerFromItem(rv);



回答3:


the answer of "Killercam" worked for me but i needed to add :

myDataGrid.UpdateLayout();

before using the GetCell methods so i'm sure i'm not getting a null reference.

to get the whole Helper class look at DataGridHelper

after all that pain, i try the whole code and i faced another probem wich is that the correctly colored cells changed during a scroll, the solution was to enable Virtualization and set its mode to Standard.

VirtualizingStackPanel.IsVirtualizing="True"
VirtualizingStackPanel.VirtualizationMode="Standard"

so, hope this will help any one who will need to iterate through datagrid cells.




回答4:


After much reading I have found a way to do what I wanted - colour cells at run-time depending on certain conditions. This is the method I use to do the colouring

public void RunChecks()
{
    const int baseColumnCount = 3;
    for (int i = baseColumnCount; i < dataGrid.Columns.Count; i++)
    {
        foreach (DataGridRow row in Utilities.GetDataGridRows(dataGrid))
        {
            if (row != null)
            {
                DataGridCell cell = dataGrid.GetCell(row, i);

                // Start work with cell.
                Color color;
                TextBlock tb = cell.Content as TextBlock;
                string cellValue = tb.Text;
                if (!CheckForBalancedParentheses(cellValue))
                    color = (Color)ColorConverter.ConvertFromString("#FF0000");
                else
                    color = (Color)ColorConverter.ConvertFromString("#FFFFFF");
                row.Background = new SolidColorBrush(color);
                //cell.Background = new SolidColorBrush(color);
            }
        }
    }
}

These are the associated utility methods required

public 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;
}

public static DataGridCell GetCell(this DataGrid grid, DataGridRow row, int column)
{
    if (row != null)
    {
        DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(row);
        if (presenter == null)
        {
            grid.ScrollIntoView(row, grid.Columns[column]);
            presenter = GetVisualChild<DataGridCellsPresenter>(row);
        }
        DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
        return cell;
    }
    return null;
}

public static IEnumerable<DataGridRow> GetDataGridRows(DataGrid grid)
{
    var itemsSource = grid.ItemsSource as IEnumerable;
    if (null == itemsSource) yield return null;
    foreach (var item in itemsSource)
    {
        var row = grid.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow;
        if (null != row) yield return row;
    }
}

Note however, that the colour of the cells move from cell to cell when the user scrolls!? This is yet another amazing annoyance of WPF. I am really confused over why something this simple can be made so so difficult. The suggestion that we need to use a MVVM-type pattern for this kind of thing I find amazing...

I hope this helps someone else.




回答5:


//the Class that resembles the Datagrid Item schema

foreach (Class cl in dgDatagrid.Items)
   {
       MessageBox.Show(cl.ID.ToString());
   }

this is the most simplest way to read the datagrid data
most articles misguide such simple things


来源:https://stackoverflow.com/questions/15657348/looping-through-wpf-datagrid-using-foreach

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!