Search code examples
c#wpfwindow

Creating a reusable WINDOW control


Okay, this seems to be very hard, or I am missing something obvious. I want to create reusable WINDOW which will be used all over the products. It means that the control is inside WPF.Controls assembly. Themes/Generic.xaml is not a solution, I need to provide my own code for the window, such as custom message hook, etc.

Here is my code in WPF.Controls.dll:

public class CustomWindow : Window
{
    static CustomWindow()
    {
        DefaultStyleKeyProperty.OverrideMetadata(
 typeof(CustomWindow),
 new FrameworkPropertyMetadata(typeof(CustomWindow)));
    }

Now, in another assembly, I create XAML file and try to use this:

<controls:CustomWindow x:Class="Views.MainWindow"
                               xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                               xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                               xmlns:controls="clr-namespace:WPF.Controls;assembly=WPF.Controls"
                               WindowStartupLocation="CenterScreen">
<TextBlock Text="TESTING" />
</controls:CustomWindow>

What I see: big black screen, nothing else, nothing less(big black rectangle - no caption bar). Can anyone shed some light over this? With a bit of googling, I found that somebody else had same problem, so I guess it's not specific to me.

Disabling hardware rendering doesn't help.


Solution

  • You need to remove the static constructor from you CustomWindow-class. The purpose of setting the DefaultStyleKey is to help WPF find your defaulttemplate that should be defined in Themes/Generic.xaml. But since you don't want to do that then you need to remove it.

    I tested your code by adding the CustomWindow class to a class library project (had to import quite a few dependencies) and then used it in a WPF project. With your constructor in place all of the content of the window was black, and once I removed it everything worked perfectly.

    This is a good resource on making your own controls

    // Chris Eelmaa: This is correct, also, I'd like to add that it's also possible to add Themes/Generic.xaml to your dll, and then you need to add the assembly ThemeInfo attribute to your DLL (AssemblyInfo.cs), in order for it to work:

    // http://blogs.magnatis.com/tim/dude-wheres-my-default-style
    [assembly: ThemeInfo(
        ResourceDictionaryLocation.None, //where theme specific 
        // resource dictionaries are located 
        ResourceDictionaryLocation.SourceAssembly //where the
        // generic resource dictionary is located 
    )]