Search code examples
.netwpfdependency-propertieswpf-style

WPF Style override Height


I have an element from third party library in my xaml file

<core:CheckBox />

It has its style in that library

<Style x:Key="{x:Type controls:CheckBox}" TargetType="{x:Type controls:CheckBox}">
    <Style.Setters>
      <Setter Property="FrameworkElement.Width" Value="170" />
      <Setter Property="FrameworkElement.Height" Value="60" />
      <Setter Property="Control.Template">
        <Setter.Value>
          <ControlTemplate TargetType="{x:Type controls:CheckBox}">
            <controls:Button x:Name="Button" 
              Width="{TemplateBinding FrameworkElement.Width}" 
              Height="{TemplateBinding FrameworkElement.Height}"
              ...
          </ControlTemplate>
        </Setter.Value>
      </Setter>
      ...
</Style>

Unfortunatelly as the Height and Width are set, it does not want to stretch.

I cannot modify the Style, which is in the third-party library. Situation has its pros, because if they change the Style, my element will have an unified look with rest of the system.

I would like to use the Style, but somehow drop Height and Width setters. Any ideas?

Edit: CheckBox is in a Grid and it does not fill the cell, that is the goal.


Solution

  • You can create your own default style based on third-party default style and reset properties there. I found a way to do it using a value converter:

    public class DummyConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return Binding.DoNothing;
            // return DependencyProperty.UnsetValue;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return Binding.DoNothing;
        }
    }
    

    This converter does nothing and doesn't provide value for binding.

    <local:DummyConverter x:Key="Resetter"/>
    <Style TargetType="{x:Type controls:CheckBox}" 
           BasedOn="{StaticResource {x:Type controls:CheckBox}}">
        <Setter Property="Height" 
                Value="{Binding RelativeSource={RelativeSource Self}, 
                                Converter={StaticResource Resetter}}"/>                    
        <Setter Property="Width" 
                Value="{Binding RelativeSource={RelativeSource Self}, 
                                Converter={StaticResource Resetter}}"/>
    </Style>
    

    Width and Height are not set intentionally