The TopLevel
The TopLevel act as the visual root, and is the base class for all top level controls, eg. Window. It handles scheduling layout, styling and rendering as well as keeping track of the client size. Most services are accessed through the TopLevel.
Getting the TopLevel
Here are two common ways to access TopLevel instance.
Using TopLevel.GetTopLevel
You can use the static GetTopLevel method of the TopLevel class to get the top-level control that contains the current control.
var topLevel = TopLevel.GetTopLevel(control);
// Here you can reference various services like Clipboard or StorageProvider from topLevel instance.
This method can be helpful if you're working within a user control or a lower-level component and need access to the TopLevel services.
If TopLevel.GetTopLevel returns null, likely control is not yet attached to the root. To ensure control is attached, you should handle Control.Loaded and Control.Unloaded events and keep track of current top level from these events.
Using the Window Class
Since theWindow class inherits from TopLevel, you can directly access services from an instance of Window:
var topLevel = window;
This method is typically used when you're already working within the context of a window, such as in a ViewModel or an event handler within the Window class.
Common Properties
ActualTransparencyLevel
Gets the achieved WindowTransparencyLevel that the platform was able to provide.
WindowTransparencyLevel ActualTransparencyLevel { get; }
ClientSize
Gets the client size of the window.
Size ClientSize { get; }
Clipboard
Gets the platform's Clipboard implementation.
IClipboard? Clipboard { get; }
FocusManager
Gets focus manager of the root.
IFocusManager? FocusManager { get; }
FrameSize
Gets the total size of the top level including system frame if presented.
Size? FrameSize { get; }