Search code examples
c#wpfmaterial-design-in-xaml

Use MaterialDesignInXamlToolkit in a WPF UserControl library


I would like to create a wpf UserControl library utilizing the MaterialDesignInXamlToolkit.

Obviously a library does not have the App.xaml file that the quick start guide suggests. I was under the impression, that I could use the Themes\Generic.xaml file plus the ThemeInfo attribute in AssemblyInfo.cs but that does not work (apparently this works only for CustomControls) - it cannot resolve the resources.

Is there a way to make this work in a wpf class library?

<Grid>
    <Button Style="{StaticResource MaterialDesignRaisedAccentButton}"
            Foreground="{StaticResource SecondaryHueLightBrush}"/>
</Grid>

Solution

  • Either install the NuGet package and reference the resource dictionaries in the App.xaml file of the consuming application, or install the package and reference the same resource dictionaries in the control itself in the library:

    <UserControl x:Class="WpfControlLibrary1.UserControl1"
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
                 xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
                 xmlns:local="clr-namespace:WpfControlLibrary1"
                 mc:Ignorable="d" 
                 d:DesignHeight="450" d:DesignWidth="800">
        <UserControl.Resources>
            <ResourceDictionary>
                <ResourceDictionary.MergedDictionaries>
                    <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Light.xaml" />
                    <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Defaults.xaml" />
                    <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Primary/MaterialDesignColor.DeepPurple.xaml" />
                    <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Accent/MaterialDesignColor.Lime.xaml" />
                </ResourceDictionary.MergedDictionaries>
            </ResourceDictionary>
        </UserControl.Resources>
        <Grid>
            <Button Style="{StaticResource MaterialDesignRaisedAccentButton}"
                Content="Test"/>
        </Grid>
    </UserControl>
    

    Make sure that the MaterialDesignThemes.Wpf and MaterialDesignColors assemblies are copied to the output directory of the app when you build:

    Dependent DLL is not getting copied to the build output folder in Visual Studio