控件样式定义中的附加属性

时间:2012-04-03 17:41:05

标签: wpf

我有以下属性定义:

public static class Extensions
{
    public static readonly DependencyProperty TestProperty = DependencyProperty.RegisterAttached("Test", typeof(Storyboard), typeof(UIElement), new UIPropertyMetadata(null));

    public static void SetTest(UIElement element, Storyboard value)
    {
         element.SetValue(TestProperty, value);
    }

    public static Storyboard GetTest(UIElement element)
    {
         return (Storyboard)element.GetValue(TestProperty);
    }
}

尝试在xaml中使用

<UserControl
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:Application;assembly=Application"
    x:Name="template"
    Height="40" Width="1460">
    <Grid Background="#FF000000">
        <TextBlock Foreground="White" VerticalAlignment="Center" HorizontalAlignment="Left" TextAlignment="Left" FontSize="32">Example</TextBlock>
    </Grid>
    <UserControl.Style>
        <Style>
            <Setter Property="local:Extensions.Test">
                <Setter.Value>
                    <Storyboard>
                        <DoubleAnimation Storyboard.TargetName="template" From="270" To="360" Duration="0:0:1" Storyboard.TargetProperty="Angle" />
                    </Storyboard>
                </Setter.Value>
            </Setter>
         </Style>
    </UserControl.Style>
</UserControl>

当我尝试加载这样的xaml时(例如使用XamlReader.Load(stream);),我得到了以下消息的异常

  

'local:Extensions.Test'属性不是“Application.Extensions”类型的有效DependencyProperty。验证属性是否具有使用以“Property”后缀结尾的成员字段定义的DependencyProperty。对象'System.Windows.Setter'出错。

有人可以帮我解决这个问题吗?

提前感谢!

1 个答案:

答案 0 :(得分:3)

所有者类型应为Extensions而非UIElement

public static readonly DependencyProperty TestProperty =
    DependencyProperty.RegisterAttached(
        "Test",
        typeof(Storyboard),
        typeof(Extensions), // here
        new UIPropertyMetadata(null)); 

也可以在没有元数据的情况下编写:

public static readonly DependencyProperty TestProperty =
    DependencyProperty.RegisterAttached(
        "Test",
        typeof(Storyboard),
        typeof(Extensions));