ResourceDictionary的自定义附加属性,带有隐式声明语法?

时间:2015-07-29 13:07:27

标签: c# wpf xaml dependency-properties attached-properties

如您所知,FrameworkElement具有名为ResourceDictionary的{​​{1}}类型的属性,在XAML中我们可以像这样容易地声明它:

Resources

这是一种隐式语法,内部声明的所有元素都将添加到 <FrameworkElement.Resources> <SomeObject x:Key="someKey"/> <SomeOtherObject x:Key="someOtherKey"/> </FrameworkElement.Resources> 。现在我想创建一个类型为ResourceDictionary的附加属性,当然需要在需要更改属性时收到通知。这是代码:

ResourceDictionary

XAML中的用法:

public static class Test
{
    public static readonly DependencyProperty TestProperty =
        DependencyProperty.RegisterAttached("Test", typeof(ResourceDictionary), 
                         typeof(Test), new PropertyMetadata(propertyChanged));
    public static ResourceDictionary GetTest(DependencyObject o)
    {
        return o.GetValue(TestProperty) as ResourceDictionary;
    }
    public static void SetTest(DependencyObject o, ResourceDictionary resource)
    {
        o.SetValue(TestProperty, resource);
    }
    static void propertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
    {

    }
}

现在,如果我运行代码,将抛出一个异常,说<Grid> <local:Test.Test> <Style TargetType="Button" x:Key="cl"></Style> </local:Test.Test> </Grid> 属性为null。我试过为附加属性提供一个默认实例,如下所示:

Test

然后它似乎运行正常,但没有任何更改通知最初。首先获取更改通知非常重要,这样我才能进行一些处理。

目前为了实现我的目标,我必须将默认值设为public static readonly DependencyProperty TestProperty = DependencyProperty.RegisterAttached("Test", typeof(ResourceDictionary), typeof(Test), new PropertyMetadata(new ResourceDictionary(), propertyChanged)); 并在XAML中使用它,如下所示:

null

这有效但不太方便,我希望它的行为与<local:Test.Test> <ResourceDictionary> <Style TargetType="Button" x:Key="cl"></Style> </ResourceDictionary> </local:Test.Test> Resources FrameworkElement属性的行为相似。 我希望这里有人有一些建议来解决这个问题。我会非常感激地接受任何想法,甚至说这是不可能的(但当然你应该确定这一点)。

0 个答案:

没有答案
相关问题