Silverlight:TargetType的属性类型无效=“{x:Type TextBlock}”

时间:2009-03-20 18:10:51

标签: .net silverlight xaml

稍微使用Silverlight并试图设置一个样式以应用于所有TextBlocks。以下XAML:

<Style TargetType="{x:Type TextBlock}">
   <Setter Property="Margin" Value="10, 10, 10, 10" />
</Style>

给我错误Invalid attribute value {x:Type TextBlock} for property TargetType.

我从MSDN复制并粘贴了这一位,所以我有点迷失为什么我收到这个错误。

编辑:

这是我现在正在尝试的完整代码:

<UserControl x:Class="NIRC.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Width="400" Height="300">
    <UserControl.Resources>
        <Style TargetType="TextBlock">
            <Setter Property="Margin" Value="10" />
            <Setter Property="Foreground" Value="Red" />
        </Style>
    </UserControl.Resources>
    <TextBlock>Hello World!</TextBlock>
</UserControl>

以下是它的外观:

alt text http://www.netortech.com/Content/slhw.jpg

6 个答案:

答案 0 :(得分:6)

Silverlight不支持通过通用样式的隐式样式(即使用TargetType但没有静态资源键 - x:Key =“”)但WPF不支持。

您需要使用StaticResource引用在要使用Style =“{StaticResource stylename }”设置样式的元素的每个实例上显式应用样式。

Silverlight toolkit有一个隐式样式管理器(ISM),它通过包装Silverlight标记并通过解析内容从ResourceDictionaries应用样式来解决这个问题。

答案 1 :(得分:4)

TargetType的值仅更改为TextBlock。它应该工作。

<Style TargetType="TextBlock">
   <Setter Property="Margin" Value="10, 10, 10, 10" />
</Style>

(可选)将x:Key和此属性的值在TextBlock中用作StaticResource。

<Style x:Key="someStyleName" TargetType="TextBlock">
   <Setter Property="Margin" Value="10, 10, 10, 10" />
</Style>
...
<TextBlock x:Name="myTextBlock" Text="Silverlight" Style="{StaticResource someStyleName}"/> 

答案 2 :(得分:4)

由于你要做的是隐式样式,到目前为止Gordon的答案似乎是正确的:“Silverlight不支持通过通用样式的隐式样式(即使用TargetType但没有静态资源键 - x:Key =” “)但WPF确实如此。”

但隐式样式适用于Silverlight 4 。见http://www.silverlightshow.net/items/Implicit-Styles-in-Silverlight-4.aspx

答案 3 :(得分:2)

嗯,以下内容应该可以工作并级联到usercontrol元素中的所有文本块。

<UserControl>
    <UserControl.Resources>
        <Style TargetType="TextBlock">
            <Setter Property="Margin" Value="10" />
        </Style>
    </UserControl.Resources>
    <TextBlock Text="This has a margin of 10 on all sides!" />
</UserControl>

编辑:
NIRC.Page是否为usercontrol提供了正确的代码隐藏?

我希望我知道出了什么问题,以下作品对我来说非常适合用户控制。

<UserControl x:Class="..."
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Height="300" Width="300">
    <UserControl.Resources>
        <Style TargetType="TextBlock">
            <Setter Property="Margin" Value="10" />
            <Setter Property="Foreground" Value="Red" />
        </Style>
    </UserControl.Resources>
    <TextBlock>Hello World!</TextBlock>
</UserControl>

结果是红色文字,所有边都有10px的边距。

答案 4 :(得分:2)

是的,Silverlight 4允许你现在进行隐式样式,你只需要做Quinton所说的,只需要设置TargetType而不用键,你就可以了。将它放在App.xaml中,它应该将样式传播到应用程序中的所有控件。

答案 5 :(得分:0)

如果您不想在每次使用控件时设置Style,可以在构造函数代码中设置它:

Style = (Style)Application.Current.Resources["YourStyle"];