Suppose that you are developing a custom control in WPF that contains internally some other basic controls. To keep it simple suppose that it contains 2 buttons.
Now you want to use this custom control in your app, but you want to restyle it a bit.
CASE 1
If, in the custom control definition, both buttons have the same style (wpf default) and you want to restyle both, it should be easy:
<mc:MyControl> <mc:MyControl.Resources> <Style x:Key={x:Type Button}, TargetType={x:Type Button}> <!-- Insert the new style here --> </Style> </mc:MyControl.Resources> <mc:MyControl>
CASE 2
If, in the custom control definition, both buttons have the same style (wpf default) but you want to restyle them with two different styles, what’s the best way to solve it?
CASE 3
If, in the custom control definition, both buttons have the same style, that refer to a Style defined inside the custom control, and you want to restyle them, what’s the best way to solve it?
Thank you in advance for all help
You could define 2 different Style properties in your custom control and bind them to the Style property of the individual buttons, thus allowing clients to set the style for the two controls independently of each other.
XAML file:
Code-behind file:
It is a good idea to implement these 2 properties as dependency properties, since that will make them conform to the other Style properties in standard WPF controls.
Now you can set the style for the buttons like you would in any WPF control:
Alternatively you could have the 2 buttons share the same Style by exposing a single property in your custom control which you bind to the Style property of both internal controls.
UPDATE
You don’t have to define the FirstButtonStyle and SecondButtonStyle properties as dependency properties. The important thing is that the internal bindings to the buttons’ Style properties are updated whenever their value changes. You can accomplish this by implementing the INotifyPropertyChanged interface in your user control and raise the OnPropertyChanged event in the property setters.
You could also assign a ‘default style’ to the 2 properties in the user control’s constructor. Here is an example: