Search code examples
c#wpfxamlwpf-controlstextblock

custom control textbox and implicit style


We are trying to make an impliced style for a custom textblock control that we made.
This custom control is base on a text block and adds a few DP and Logic.
When we use the style locally everything works fine. Also when we give the style a key it also works.

This is the custom control inheritince code:

public class HighlightTextBlock : TextBlock

and this is the style:

    <Style TargetType="UI:HighlightTextBlock"
       x:Name="LocalHighlightTextBlockStyle"
       BasedOn="{StaticResource StyleHighlightTextBlockDefault}">
  <Setter Property="HighlightedText"
          Value="{Binding ElementName=txtSearchBox, Path=Text}"></Setter> 
  <Setter Property="Background" Value="Tomato"></Setter>
  <!--<Setter Property="HighlightedText" Value="{Binding UpdateSourceTrigger=PropertyChanged,
              Mode=TwoWay, RelativeSource={RelativeSource FindAncestor, 
              AncestorType={x:Type UI:GenericWatchControl}}, Path=SearchTextBoxContent}" />-->
  <!--<Style.Triggers>
    <Trigger Property="Text" Value="{x:Static ProfilingServerShared:MissingDataValue.NotAvailableText}">
      <Setter Property="Foreground" Value="LightGray" />
    </Trigger>
  </Style.Triggers>-->
</Style>

Thanks all


Solution

  • You should override metadata in HighlightTextBlock static constructor, as such:

    public partial class HighlightTextBlock : TextBlock
    {
        static HighlightTextBlock()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(HighlightTextBlock), 
              new FrameworkPropertyMetadata(typeof(HighlightTextBlock)));
        }
    }
    

    If you do not do this, by default, the HighlightTextBlock will try to find implicit style for TextBlock, not HighglightTextBlock.