C# InvalidOperationException:只能基于目标类型为基本类型';文本块';
我创建了一种称为baseStyle的样式,如下所示:C# InvalidOperationException:只能基于目标类型为基本类型';文本块';,c#,.net,wpf,xaml,C#,.net,Wpf,Xaml,我创建了一种称为baseStyle的样式,如下所示: <Style TargetType="{x:Type Control}" x:Key="baseStyle"> <Setter Property="FontSize" Value="30" /> <Setter Property="FontFamily" Value="Saumil_guj2" /> </Style> 现在是抱怨。我的意思是它给了我解释: InvalidOper
<Style TargetType="{x:Type Control}" x:Key="baseStyle">
<Setter Property="FontSize" Value="30" />
<Setter Property="FontFamily" Value="Saumil_guj2" />
</Style>
现在是抱怨。我的意思是它给了我解释:
InvalidOperationException: Can only base on a Style with target type
that is base type 'TextBlock'.
所以,我查了MSDN
在那里,我发现ListBoxItem间接派生自System.Windows.Controls。可以找到它
在那里,我还发现TextBlock也来自System.Windows.Controls。可以找到它
因此,我不明白为什么会出现这个错误?如注释
TextBlock
中所述,它不是从控件派生的,而是直接从框架元素派生的。TextBlock
和Control
之间没有具有FontSize
和FontFamily
的公共类。它们都是单独实现的。您可以做什么呢?为FrameworkElement
创建样式,设置附加属性TextElement.FontSize
和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>
TextBlock
不是从控件派生的,而是直接从框架元素派生的。TextBlock
和Control
之间没有具有FontSize
和FontFamily
的公共类。他们都实施了这一计划separately@dkozl你应该这样回答。谢谢@dkozl。那很好用。发布此问题后,我尝试了FrameworkElement,但我遇到了另一个错误,因为它不包含FontSize和FontFamily。现在我学到了新的一课。在这种情况下,我应该使用TextElement.FontSize。再次感谢你。
InvalidOperationException: Can only base on a Style with target type
that is base type 'TextBlock'.
<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>