WindowStartupLocation is a CLR property, this can be seen in ILSpy :
[DefaultValue(WindowStartupLocation.Manual)] public WindowStartupLocation WindowStartupLocation { get { this.VerifyContextAndObjectState(); this.VerifyApiSupported(); return this._windowStartupLocation; } set { this.VerifyContextAndObjectState(); this.VerifyApiSupported(); if (!Window.IsValidWindowStartupLocation(value)) { throw new InvalidEnumArgumentException("value", (int)value, typeof(WindowStartupLocation)); } this._windowStartupLocation = value; } }
In style settings, only a dependency property can be specified. There are two ways to solve this problem:
inherit the Window class and create a class with the WindowStartupLocation dependency WindowStartupLocation
create a related property type dependent on WindowStartupLocation and define the logic in PropertyChanged
The first method is cumbersome because you need to override the class for a single property. The second method is preferred and the behavior will be applied, but I will call PropertyExtension .
Here is the complete code:
namespace YourProject.PropertiesExtension { public static class WindowExt { public static readonly DependencyProperty WindowStartupLocationProperty; public static void SetWindowStartupLocation(DependencyObject DepObject, WindowStartupLocation value) { DepObject.SetValue(WindowStartupLocationProperty, value); } public static WindowStartupLocation GetWindowStartupLocation(DependencyObject DepObject) { return (WindowStartupLocation)DepObject.GetValue(WindowStartupLocationProperty); } static WindowExt() { WindowStartupLocationProperty = DependencyProperty.RegisterAttached("WindowStartupLocation", typeof(WindowStartupLocation), typeof(WindowExt), new UIPropertyMetadata(WindowStartupLocation.Manual, OnWindowStartupLocationChanged)); } private static void OnWindowStartupLocationChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) { Window window = sender as Window; if (window != null) { window.WindowStartupLocation = GetWindowStartupLocation(window); } } } }
Usage example:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:PropertiesExtension="clr-namespace:YourProject.PropertiesExtension"> <Style TargetType="{x:Type Window}"> <Setter Property="PropertiesExtension:WindowExt.WindowStartupLocation" Value="CenterScreen" /> <Setter Property="Width" Value="723" /> <Setter Property="Height" Value="653" /> <Setter Property="Title" Value="MainWindow title string" /> </Style> </ResourceDictionary>
Anatoliy Nikolaev
source share