Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

InvalidOperationException: Can only base on a Style with target type that is base type 'TextBlock'

Tags:

c#

.net

wpf

xaml

I have created a style called baseStyle like this:

<Style TargetType="{x:Type Control}" x:Key="baseStyle">
    <Setter Property="FontSize" Value="30" />
    <Setter Property="FontFamily" Value="Saumil_guj2" />
</Style>

Then I used it for a ListBoxItem like:

<Style TargetType="{x:Type ListBoxItem}" BasedOn="{StaticResource baseStyle}">

</Style>

It happily accepts the FontSize and FontFamily from baseStyle.

I tried to do a similar thing for TextBlock:

<Style TargetType="{x:Type TextBlock}" BasedOn="{StaticResource baseStyle}">

</Style>

Now its complaining. I mean It gave me exeption:

InvalidOperationException: Can only base on a Style with target type 
that is base type 'TextBlock'.

So, I checked on MSDN.

There I found that ListBoxItem derives indirectly from System.Windows.Controls. It can be found here.

There I also found that TextBlock also derives from System.Windows.Controls. It can be found here.

So, I don't understand why am I getting this error?

like image 846
Vishal Avatar asked Aug 30 '14 19:08

Vishal


1 Answers

As mentioned in the comment TextBlock does not derive from Control but straight from FrameworkElement. There is no common class between TextBlock and Control that has FontSize and FontFamily. They both implement it separately. What you could do it create style for FrameworkElement that sets attached properties TextElement.FontSize and TextElement.FontFamily

<Style TargetType="{x:Type FrameworkElement}" x:Key="baseStyle">
    <Setter Property="TextElement.FontSize" Value="30" />
    <Setter Property="TextElement.FontFamily" Value="Saumil_guj2" />
</Style>
<Style TargetType="{x:Type ListBoxItem}" BasedOn="{StaticResource baseStyle}">

</Style>
<Style TargetType="{x:Type TextBlock}" BasedOn="{StaticResource baseStyle}">

</Style>
like image 196
dkozl Avatar answered Sep 27 '22 02:09

dkozl