0

I created a custom control and defined a style for it. I would like that style to be applied automatically when using the control.

Right now my code is structured like this:

The custom control inherits from ProgressBar

namespace MyProjectNamespace
{
    [TemplatePart(Name = SomePartName, Type = typeof(PathFigure))]
    public class RadialProgressBar : ProgressBar
    {
        // class definitions and logic
    }
}

And the style is defined in a ResourceDictionary called RadialProgressBar.xaml

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:MyProjectNamespace">

    <Style TargetType="local:RadialProgressBar">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="local:RadialProgressBar">
                    <!-- controls -->
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

When I have to use the control, I have to reference the ResourceDictionary like this:

<Window x:Class="FWUpdateLoadingSpinner.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:MyProjectNamespace"
        mc:Ignorable="d"
        Title="MainWindow" Height="300" Width="300">
    <Window.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="RadialProgressBar.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Window.Resources>
    <local:RadialProgressBar />
</Window>

Is it possible to make it so I don't have to define the ResourceDictionary when I want to use the control? To just have a default template like normal .NET controls (which can be overridden).

This is part of a big project and I would like to keep this separated from files like App.xaml if possible.

Daltons
  • 2,671
  • 2
  • 18
  • 24
  • 1
    The default Style of a custom control resides in a specialized ResourceDictionary `Themes\Generic.xaml`. You also need to set (or override the default value of) the `DefaultStyleKey` property. All this is generated by Visual Studio if you add a *Custom Control* to a WPF project. – Clemens Aug 15 '19 at 13:54
  • Thanks for info. Especially that VS generates the files automatically (and describes how to use them). – Daltons Aug 15 '19 at 14:17

0 Answers0