...Blah......">

Implicit styles not working on user controls

In my App.xaml I have some implicit styles

<Style TargetType="{x:Type Button}"> ...Blah... </Style> 

These styles work for control until they are in the custom control that I create.

My control

  public class NavigationControl : Control { public static readonly DependencyProperty ButtonStyleProperty = DependencyProperty.Register("ButtonStyle", typeof(Style), typeof(NavigationControl)); public Style ButtonStyle { get { return (Style)GetValue(ButtonStyleProperty); } set { SetValue(ButtonStyleProperty, value); } } } static NavigationControl() { DefaultStyleKeyProperty.OverrideMetadata(typeof(NavigationControl), new FrameworkPropertyMetadata(typeof(NavigationControl))); } public NavigationControl() { } 

My styles and management templates

 <ControlTemplate x:Key="NavigationControlTemplate" TargetType="{x:Type controls:NavigationControl}"> <Button Style="{TemplateBinding ButtonStyle}" </ControlTemplate> <Style x:Key="DefaultButtonStyle" TargetType="{x:Type Button}" BasedOn="{StaticResource {x:Type Button}}"> <Setter Property="MinWidth" Value="75"/> <Setter Property="Height" Value="50"/> <Setter Property="FontSize" Value="12"/> <Setter Property="Margin" Value="-1"/> </Style> <Style x:Key="ButtonStyle" TargetType="{x:Type Button}" BasedOn="{StaticResource DefaultButtonStyle}"> <Setter Property="Template" Value="{StaticResource NavigationButtonTemplate}"/> </Style> <Style TargetType="{x:Type controls:NavigationControl}"> <Setter Property="Template" Value="{StaticResource NavigationControlTemplate}"/> <Setter Property="ButtonStyle" Value="{StaticResource ButtonStyle}"/> </Style> 

Now I would suggest that DefaultButtonStyle BasedOn will get it from the App level. But this is not so. The only way to apply an application-level style is to override ButtonStyle by creating a style of type NavigationControl.

Is there a way in which implicit style does this work?

+6
source share
1 answer

Setting BasedOn="{StaticResource {x:Type Button}}" will get the default WPF style style. If you want to use the style defined in App.xaml , you need to add a key to this style so that you can reference it from your control style:

App.xaml

 <!-- Your style, just with an added x:Key --> <Style x:Key="myButtonStyle" TargetType="{x:Type Button}"> ... </Style> <!-- Set the above style as a default style for all buttons --> <Style TargetType="{x:Type Button}" BasedOn="{StaticResource myButtonStyle}"> 

Management styles and patterns

 <Style x:Key="DefaultButtonStyle" TargetType="{x:Type Button}" BasedOn="{StaticResource myButtonStyle}"> ... </Style> 
+2
source

Source: https://habr.com/ru/post/952393/


All Articles