This guide expands on the FAQ and shows how layouts can be serialized and restored using the available serializers.
Dock provides multiple serialization options:
Dock.Serializer.Newtonsoft
- JSON serialization using Newtonsoft.JsonDock.Serializer.SystemTextJson
- JSON serialization using System.Text.JsonDock.Serializer.Protobuf
- Binary serialization using protobuf-netDock.Serializer.Xml
- XML serializationDock.Serializer.Yaml
- YAML serializationAll serializers implement IDockSerializer
and work with DockState
to track focus changes. The code snippets below use asynchronous file APIs but any Stream
works.
using Dock.Serializer;
var serializer = new DockSerializer();
using Dock.Serializer.SystemTextJson;
var serializer = new DockSerializer();
using Dock.Serializer.Protobuf;
var serializer = new ProtobufDockSerializer();
using Dock.Serializer.Xml;
var serializer = new DockXmlSerializer();
using Dock.Serializer.Yaml;
var serializer = new DockYamlSerializer();
Persist the current layout when the application closes so the user can continue where they left off.
await using var stream = File.Create("layout.json");
_serializer.Save(dockControl.Layout!, stream);
dockControl.Layout
must reference the current IDock
root. The serializer writes JSON to the stream.
When starting the application, load the previously saved layout and restore the last active and focused dockables.
await using var stream = File.OpenRead("layout.json");
var layout = _serializer.Load<IDock?>(stream);
if (layout is { })
{
dockControl.Layout = layout;
_dockState.Restore(layout); // reapply focus information
}
Before calling Load
ensure that custom dockables are registered with DockableLocator
and ContextLocator
. Unknown identifiers return null
.
DockableLocator
at startup.dockControl.Layout
with DockSerializer
._dockState.Restore
.Following this pattern keeps the window arrangement consistent across sessions.
Every dockable stores an Id
string that is written to the layout file. During
deserialization DockableLocator
receives this identifier and returns the view
model to instantiate. The value is a type key, not a unique runtime ID. When a
document dock is split or cloned the framework copies the original Id
so each
section resolves to the same view model type. Track your own unique identifier
if your application must distinguish individual document docks.
For an overview of all guides see the documentation index.