开发者

Loop through all cells in Xceed DataGrid for WPF?

开发者 https://www.devze.com 2022-12-16 22:53 出处:网络
I am changing the background color of the cells when the user has made an edit. I would like to return all cells to normal colors when the changes are saved (or reverted).

I am changing the background color of the cells when the user has made an edit. I would like to return all cells to normal colors when the changes are saved (or reverted).

It's easy enough to set the cell's original background color (as stored in the parent row). But I can't figure out how to loop through all the cells in the table to reset them.

I found an article in the Xceed Knowledge Base called "How to iterate through the grid's rows"... which you would think would be perfect, right? Wrong; the properties (or methods) like .DataRows, .FixedHeaderRows, etc. mentioned in 开发者_Python百科the article are from an older/defunct Xceed product.

This forum thread recommends using the DataGrid's .Items property, which in my case returns a collection of System.Data.DataRowViews... but I can't find any way to cast that (or any of its related elements) up to the Xceed.Wpf.DataGrid.DataCells I need to change the background color.

In short, how do I loop through the rows and cells so I can reset the background property?


The question has been resolved, thanks to Mohamed, an Xceed employee who posted on the Xceed Forums. Example code follows:

foreach (object item in this.DataGrid1.Items)
{
    Dispatcher.BeginInvoke(new Action<object>(RemoveRowHighlights), DispatcherPriority.ApplicationIdle, item);
}
...
private void RemoveRowHighlights(object item)
{
    Xceed.Wpf.DataGrid.DataRow row = this.DataGrid1.GetContainerFromItem(item) as Xceed.Wpf.DataGrid.DataRow;
    if (row != null) foreach (Xceed.Wpf.DataGrid.DataCell c in row.Cells)
    {
        if (c != null) c.Background = row.Background;
    }
}


I propose that you change your business logic to utilize data binding instead.

Each cell in your data grid would then be an object, which itself knows if it has been edited or not. And then you can data bind to that property, and therefore when you save and reset all of your objects, the status will also be updated in your gui.

Also, you get a separation of concerns for free. You GUI now decides how things should LOOK, not what the business logic of tracking saved/not saved should be.


The recommended way to do this is through an implicit style trigger (because of UI virtualization), and all properties on Xceed DataGrid are settable, except those imposed by the theme defined on the DataGrid.

e.g. :

  <Style TargetType="{x:Type xcdg:DataCell }">
     <Style.Triggers>
        <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=IsDirty}"
                     Value="True">
           <Setter Property="Background"
                   Value="DeepSkyBlue" />
        </DataTrigger>
     </Style.Triggers>
  </Style>
0

精彩评论

暂无评论...
验证码 换一张
取 消