InvalidOperationException:只能基于具有基类型"TextBlock"的目标类型的Style

Vis*_*hal 8 .net c# wpf xaml

我创建了一个名为baseStyle的样式,如下所示:

<Style TargetType="{x:Type Control}" x:Key="baseStyle">
    <Setter Property="FontSize" Value="30" />
    <Setter Property="FontFamily" Value="Saumil_guj2" />
</Style>
Run Code Online (Sandbox Code Playgroud)

然后我用它作为ListBoxItem,如:

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

</Style>
Run Code Online (Sandbox Code Playgroud)

它乐意接受FontSizeFontFamily来自baseStyle.

我试着为TextBlock做类似的事情:

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

</Style>
Run Code Online (Sandbox Code Playgroud)

现在它抱怨.我的意思是它给了我的例外:

InvalidOperationException: Can only base on a Style with target type 
that is base type 'TextBlock'.
Run Code Online (Sandbox Code Playgroud)

所以,我在MSDN上查了一下.

在那里我发现ListBoxItem间接地从System.Windows.Controls派生.它可以在这里找到.

在那里我还发现TextBlock也派生自System.Windows.Controls.它可以在这里找到.

所以,我不明白为什么我会收到这个错误?

dko*_*ozl 18

正如评论TextBlock中提到的那样,并非Control直接来自FrameworkElement.之间不存在通用类TextBlockControlFontSizeFontFamily.他们都分开实施.你可以做什么创建样式FrameworkElement设置附加属性TextElement.FontSizeTextElement.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>
Run Code Online (Sandbox Code Playgroud)