I have a custom control derived from Button:
class MyControl : Button{}
And suppose, this class is empty (has no members).
In the application's main window resources I use ResourceDictionary that contains styles for most WPF controls (so called theme):
<ResourceDictionary Source="BureauBlue.xaml" />
So, all controls on the window look like it is defined in that theme file. But the styles are not affected on MyControl controls. How can I do MyControl to look same as a Button controls?
Update: The style for Button in BureauBlue.xaml has no key and is defined in the following way:
<Style TargetType="{x:Type Button}" BasedOn="{x:Null}"> ...</Style>
Create a new WPF project and then right-click on your solution and select Add > New Item... It will open the following window. Now select Custom Control (WPF) and name it MyCustomControl. Click the Add button and you will see that two new files (Themes/Generic.
A customControl can be styled and templated and best suited for a situation when you are building a Control Library. On the contrary, a UserControl gives you an easy way to define reusable chunk of XAML which can be reused widely in your application and when you don't need to use it as a Control Library .
Content Control is a base class that provides standardised functionality to WPF Controls. The Content Control class represents controls that can include a single item of content. This content is commonly plain text or a child control. Content Control is a subclass of the Control class in WPF.
For doing this completely in code this answer on another forum works
this.Style = new Style(GetType(), this.FindResource(typeof(System.Windows.Controls.Button)) as Style);
I use SetResourceReference
SetResourceReference(StyleProperty, typeof(Button));
You override the DefaultStyleKey's metadata in your static constructor:
static MyControl()
{
DefaultStyleKeyProperty.OverrideMetadata(
typeof(MyControl),
new FrameworkPropertyMetadata(typeof(MyControl)));
}
Then, in your resources, you can base its style on the button:
<Style TargetType="{x:Type lcl:MyControl}" BasedOn="{StaticResource {x:Type Button}}" />
I've tried in the past to override the DefaultStyleKey's metadata to point to the base class (Button in your case), but it doesn't seem to work.
The TargetType property doesn't work for classes that derive from the specified type. See this question
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With