对于那些为解决问题而苦苦挣扎的人:如何将自定义样式自动应用于我的所有 Window 派生类型?以下是我想出的解决方案
注意:出于特定于我的项目的原因(我的产品的消费者使用我的通用可重用样式库并创建自己的布局/窗口等)所以我真的很想找出一个可行的解决方案,我愿意忍受任何副作用
需要遍历所有实例化的窗口并简单地强制它们使用您为 Window 类型定义的新自定义样式。这对于已经启动的窗口非常有用,但是当实例化窗口或子窗口时,它不会知道使用已为其基类型声明的新/自定义类型;香草窗口类型。所以我能想到的最好的办法是在 MainWindow 上使用 LostKeyBoardFocus 以在它失去对 ChildWindow 的焦点时(IOW 当创建子窗口时),然后调用这个 FixupWindowDerivedTypes()。
如果有人在实例化任何类型的窗口派生类型时有更好的“检测”解决方案并因此调用 FixupWindowDerivedTypes() 那就太好了。在此区域中处理 WM_WINDOWPOSCHANGING 可能也有一些用处。
因此,这个解决方案并不优雅,但无需我接触任何与我的窗口相关的代码或 XAML 就可以完成工作。
public static void FixupWindowDerivedTypes()
{
foreach (Window window in Application.Current.Windows)
{
//May look strange but kindly inform each of your window derived types to actually use the default style for the window type
window.SetResourceReference(FrameworkElement.StyleProperty, DefaultStyleKeyRetriever.GetDefaultStyleKey(window));
}
}
}
}
//Great little post here from Jafa to retrieve a protected property like DefaultStyleKey without using reflection.
http://themechanicalbride.blogspot.com/2008/11/protected-dependency-properties-are-not.html
//Helper class to retrieve a protected property so we can set it
internal class DefaultStyleKeyRetriever : Control
{
/// <summary>
/// This method retrieves the default style key of a control.
/// </summary>
/// <param name="control">The control to retrieve the default style key
/// from.</param>
/// <returns>The default style key of the control.</returns>
public static object GetDefaultStyleKey(Control control)
{
return control.GetValue(Control.DefaultStyleKeyProperty);
}
}