WindowStartupLocation
是一个 CLR 属性,这可以在以下位置看到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;
}
}
在样式设置器中只能指定依赖属性。有两种方法可以解决这个问题:
第一种方法比较麻烦,因为需要为一个属性重新定义类。第二种方法是首选,并且会附加行为,但我会调用PropertyExtension
.
这是完整的代码:
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);
}
}
}
}
使用示例:
<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>