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>
<Window WindowStartupLocation="CenterOwner" />
语法)设置CLR(非依赖项)属性,但不能从资源字典中设置,对吗? - User3810621StaticResource
,因为我需要从Window
引用ResourceDictionary
(我正在开发一个Office插件,它没有WPFApplication
类)。但是您的建议非常适合在Windows应用程序中集中默认样式。 - User3810621