wpf InvalidOperationException:只能基于目标类型为“TextBlock”的样式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25586037/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
InvalidOperationException: Can only base on a Style with target type that is base type 'TextBlock'
提问by Vishal
I have created a style called baseStyle like this:
我创建了一个名为 baseStyle 的样式,如下所示:
<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:
然后我将它用于 ListBoxItem ,例如:
<Style TargetType="{x:Type ListBoxItem}" BasedOn="{StaticResource baseStyle}">
</Style>
It happily accepts the FontSizeand FontFamilyfrom baseStyle.
它愉快地接受FontSize和FontFamilyfrom baseStyle。
I tried to do a similar thing for TextBlock:
我试图为 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.
所以,我检查了MSDN。
There I found that ListBoxItem derives indirectly from System.Windows.Controls. It can be found here.
在那里我发现 ListBoxItem 间接从 System.Windows.Controls 派生。可以在这里找到。
There I also found that TextBlock also derives from System.Windows.Controls. It can be found here.
在那里,我还发现 TextBlock 也源自 System.Windows.Controls。可以在这里找到。
So, I don't understand why am I getting this error?
所以,我不明白为什么我会收到这个错误?
回答by dkozl
As mentioned in the comment TextBlockdoes not derive from Controlbut straight from FrameworkElement. There is no common class between TextBlockand Controlthat has FontSizeand FontFamily. They both implement it separately. What you could do it create style for FrameworkElementthat sets attached properties TextElement.FontSizeand TextElement.FontFamily
正如评论TextBlock中提到的,不是来自Control而是直接来自FrameworkElement. TextBlockand之间没有Control具有FontSizeand 的公共类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>

