For those struggling with a solution to the problem: how can I automatically customize my own style for all of my derived Window types? Below is the solution I came up with
NOTE. I really did not want to deduce from type Window or to insert XAML in each window to force to update style, etc. for reasons specific to my project (the consumers of my product used our universal library of reusable styles and create their own layout / windows, etc.), so I was really motivated to understand what kind of solution I got that I’m ready to live with any side effects.
You need to iterate over all created instances of the window and just force them to use the new custom style that you defined for the Window type. This is great for windows that are already created, but when a window or child window is created, it will not know if to use the new / user type that was declared for its base type; type of vanilla window. Therefore, it would be best to use LostKeyBoardFocus in MainWindow when it loses Focus in ChildWindow (IOW when the child window was created) and then calls this FixupWindowDerivedTypes ().
If someone has a better solution to “detect” when some type of window-derived is created, and so FixupWindowDerivedTypes () is called, which would be great. There might be something useful in handling WM_WINDOWPOSCHANGING in this area.
So, this solution is not elegant for everyone, but does its job without me to touch on any code or XAML associated with my windows.
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); } }
Arnie May 10 '13 at 17:06 2013-05-10 17:06
source share