Back to Devexpress

Save and Restore Layout

wpf-6797-controls-and-libraries-data-grid-miscellaneous-save-and-restore-layout.md

latest11.3 KB
Original Source

Save and Restore Layout

  • Sep 12, 2022
  • 5 minutes to read

The GridControl allows you to save the information on its layout to a data store (an XML file or stream) and restore it when required. This information may include the visibility, position and size of visual elements, filter, sorting, grouping, and summary information, etc. Multiple options allow you to specify which settings need to be saved and restored when the layout is saved/restored.

To save the grid’s layout, use the DataControlBase.SaveLayoutToStream or DataControlBase.SaveLayoutToXml methods.

To restore the layout, use the DataControlBase.RestoreLayoutFromStream or DataControlBase.RestoreLayoutFromXml method.

To correctly save and restore the grid layout, grid columns and bands should be uniquely identified. Use the x:Name attribute to uniquely identify grid bands and grid columns.

Set the DataControlBase.UseFieldNameForSerialization property to true (it is set to true by default) to uniquely identify the grid columns and use their bound field name as a unique value.

If you generate the control’s elements from a View Model collection, you cannot use bindings to define the element’s Name property. Instead, use the DevExpress.Xpf.Core.XamlHelper.Name attached property to pass the name specified in a View Model to the element’s Name property:

xaml
<DataTemplate x:Key="BandTemplate">
    <dxg:GridControlBand ...
        dx:XamlHelper.Name="{Binding Path=(dxci:DependencyObjectExtensions.DataContext).UniqueName, RelativeSource={RelativeSource Self}}"/>
</DataTemplate>

Layout Options

The DXSerializer.StoreLayoutMode specifies which settings should be saved. The property values:

  • None - nothing is saved or restored.
  • All - all settings are saved/restored. These include the visual, data-aware, behavior, customization options, etc.
  • UI (Default Value) - only those settings that are marked with the GridUIProperty attribute are saved/restored. These include visibility state, position and size of columns, sorting and grouping settings, summary information, etc.

To manually control which settings should be serialized, handle the DXSerializer.AllowProperty event:

csharp
using DevExpress.Xpf.Core.Serialization;
using DevExpress.Xpf.Grid;
// ...

public partial class MainWindow : Window {
    public MainWindow() {
        //...
        grid.Columns[nameof(Customer.ID)].AddHandler(DXSerializer.AllowPropertyEvent, 
              new AllowPropertyEventHandler(OnAllowProperty));
    }

    void OnAllowProperty(object sender, AllowPropertyEventArgs e) {
        if (e.DependencyProperty == GridColumn.WidthProperty)
            e.Allow = false;
    }
}
vb
Imports DevExpress.Xpf.Core.Serialization
Imports DevExpress.Xpf.Grid
'...

Public Partial Class MainWindow
    Inherits Window

    Public Sub New()
        ' ...
        grid.Columns(NameOf(Customer.ID)).[AddHandler](DXSerializer.AllowPropertyEvent, 
            New AllowPropertyEventHandler(AddressOf OnAllowProperty))
    End Sub

    Private Sub OnAllowProperty(ByVal sender As Object, ByVal e As AllowPropertyEventArgs)
        If e.DependencyProperty = GridColumn.WidthProperty Then e.Allow = False
    End Sub
End Class

View Example: Exclude GridControl's Properties from Serialization

Note

The GridControl does not support serialization of the *Style and *Template properties because of the following points:

  • There is no general way to serialize such complex objects like Style or Template.
  • Serialization is used to save/restore properties that can be changed by an end user, but there is no capability to change Style or Template at runtime (unless you provide this functionality manually).

The GridControl does not support serialization of the applied filter if it contains custom or enumeration objects.

Layout Loading Specifics

There are two options that specify what to do with the columns that exist in the layout being loaded, but not in the current grid. By default, the columns that exist in the current grid but not in the layout being loaded are retained. Also, the columns that exist in the layout being loaded but do not exist in the current grid’s layout are destroyed. To change this behavior, use the DataControlSerializationOptions.AddNewColumns and DataControlSerializationOptions.RemoveOldColumns properties.

Example

This example shows how to save the GridControl‘s layout to a memory stream. To do this, click the Save Layout button. Click the Restore Layout button to restore the saved layout.

View Example: Save Layout and Restore It from a Memory Stream

xaml
<dxg:GridControl x:Name="grid"
                 dx:DXSerializer.StoreLayoutMode="All" 
                 dxg:GridSerializationOptions.AddNewColumns="False" 
                 dxg:GridSerializationOptions.RemoveOldColumns="False"
                 UseFieldNameForSerialization="True">
    <dxg:GridColumn FieldName="IssueName"/>
    <dxg:GridColumn FieldName="IssueType"/>
    <dxg:GridColumn FieldName="IsPrivate" Header="Private"/>
    <dxg:GridControl.View>
        <dxg:TableView AutoWidth="True"/>
    </dxg:GridControl.View>
</dxg:GridControl>

<StackPanel Grid.Row="1" Orientation="Vertical">
    <StackPanel Orientation="Horizontal">
        <Button Margin="1" Content="Add a New Column" Click="OnAddNewColumn"/>
    </StackPanel>
    <StackPanel Orientation="Horizontal">
        <Button Content="Save Layout" Margin="1" Click="OnSaveLayout"/>
        <Button Content="Restore Layout" Margin="1" Click="OnRestoreLayout"/>
    </StackPanel>
</StackPanel>
cs
public partial class Window1 : Window {
    MemoryStream layoutStream;
    public Window1() {
        InitializeComponent();
        grid.ItemsSource = IssueList.GetData();
    }

    void OnSaveLayout(object sender, RoutedEventArgs e) {
        layoutStream = new MemoryStream();
        grid.SaveLayoutToStream(layoutStream);
    }
    void OnRestoreLayout(object sender, RoutedEventArgs e) {
        layoutStream.Position = 0;
        grid.RestoreLayoutFromStream(layoutStream);
    }
    void OnAddNewColumn(object sender, RoutedEventArgs e) {
        grid.Columns.Add(new DevExpress.Xpf.Grid.GridColumn() { FieldName = "IsPrivate" });
    }
}
vb
Public Partial Class Window1
    Inherits Window

    Private layoutStream As MemoryStream

    Public Sub New()
        Me.InitializeComponent()
        Me.grid.ItemsSource = IssueList.GetData()
    End Sub

    Private Sub OnSaveLayout(ByVal sender As Object, ByVal e As RoutedEventArgs)
        layoutStream = New MemoryStream()
        Me.grid.SaveLayoutToStream(layoutStream)
    End Sub

    Private Sub OnRestoreLayout(ByVal sender As Object, ByVal e As RoutedEventArgs)
        layoutStream.Position = 0
        Me.grid.RestoreLayoutFromStream(layoutStream)
    End Sub

    Private Sub OnAddNewColumn(ByVal sender As Object, ByVal e As RoutedEventArgs)
        Me.grid.Columns.Add(New DevExpress.Xpf.Grid.GridColumn() With {.FieldName = "IsPrivate"})
    End Sub
End Class

Restore State On Source Change

Set the DataControlBase.RestoreStateOnSourceChange property to true to retain the control’s select, focus, check, and group states when a new ItemsSource is assigned.

xaml
<dxg:GridControl Name="grid" ItemsSource="{Binding Items}" AutoGenerateColumns="AddNew" SelectionMode="Row" 
                 RestoreStateOnSourceChange="True" RestoreStateKeyFieldName="ID">
    <dxg:GridControl.View>
        <dxg:TableView />
    </dxg:GridControl.View>
</dxg:GridControl>
csharp
public class ViewModel : ViewModelBase {
    public ObservableCollection<Item> Items {
        get { return GetValue<ObservableCollection<Item>>(nameof(Items)); }
        private set { SetValue(value, nameof(Items)); }
    }
}
public class Item : BindableBase {
    public string Name {
        get { return GetValue<string>(nameof(Name)); }
        set { SetValue(value, nameof(Name)); }
    }
    public int ID { 
        get { return GetValue<int>(nameof(ID)); }
        set { SetValue(value, nameof(ID)); }
    }      
    public int GroupID {
        get { return GetValue<int>(nameof(GroupID)); }
        set { SetValue(value, nameof(GroupID)); }
    }
}
vb
Public Class ViewModel
    Inherits ViewModelBase

    Public Property Items As ObservableCollection(Of Item)
        Get
            Return GetValue(Of ObservableCollection(Of Item))(NameOf(Items))
        End Get
        Private Set(ByVal value As ObservableCollection(Of Item))
            SetValue(value, NameOf(Items))
        End Set
    End Property
End Class

Public Class Item
    Inherits BindableBase

    Public Property Name As String
        Get
            Return GetValue(Of String)(NameOf(Name))
        End Get
        Set(ByVal value As String)
            SetValue(value, NameOf(Name))
        End Set
    End Property

    Public Property ID As Integer
        Get
            Return GetValue(Of Integer)(NameOf(ID))
        End Get
        Set(ByVal value As Integer)
            SetValue(value, NameOf(ID))
        End Set
    End Property

    Public Property GroupID As Integer
        Get
            Return GetValue(Of Integer)(NameOf(GroupID))
        End Get
        Set(ByVal value As Integer)
            SetValue(value, NameOf(GroupID))
        End Set
    End Property
End Class