依赖属性用法

时间:2012-11-18 13:52:52

标签: wpf xaml dependency-properties attached-properties

我有一个工作附加行为,我想添加DP。我可以在XAML中设置属性,但是当我尝试访问它时它是null。

修复是什么?

干杯,
Berryl

XAML

<Button Command="{Binding ContactCommand}" local:ContactCommandBehavior.ResourceKey="blah" >
    <i:Interaction.Behaviors>
        <local:ContactCommandBehavior />
    </i:Interaction.Behaviors>
</Button>

行为代码

internal class ContactCommandBehavior : Behavior<ContentControl>
{
    ...

    public static readonly DependencyProperty ResourceKeyProperty = 
        DependencyProperty.RegisterAttached("ResourceKey", typeof(string), typeof(ContactCommandBehavior));

    public static string GetResourceKey(FrameworkElement element)
    {
        return (string)element.GetValue(ResourceKeyProperty);
    }

    public static void SetResourceKey(FrameworkElement element, string value)
    {
        element.SetValue(ResourceKeyProperty, value);
    }

    private void SetProperties(IHaveDisplayName detailVm)
    {

        //************ 
        var key = GetResourceKey(AssociatedObject);
        //************ 
        ....
    }

}

编辑HighCore。

我按如下方式更改代码,将RegisterAttached更改为Register并使属性非静态。当我尝试通过

时,该值仍为null
public static readonly DependencyProperty ResourceKeyProperty =
    DependencyProperty.Register("ResourceKey", typeof (string), typeof (ContactCommandBehavior));

public string ResourceKey
{
    get { return (string)GetValue(ResourceKeyProperty); }
    set { SetValue(ResourceKeyProperty, value); }
}

protected override void OnAttached() {
    base.OnAttached();
    if (AssociatedObject == null)
        throw new InvalidOperationException("AssociatedObject must not be null");

    AssociatedObject.DataContextChanged += OnDataContextChanged;
    CultureManager.UICultureChanged += OnCultureChanged;
}

private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e) {
    // do some setup stuff
    SetProperties(vm)
}

private void SetProperties(IHaveDisplayName detailVm)
{
    ////////////////////////////////
    var key = ResourceKey.Replace(TOKEN, cmType);
    /////////////////////////////////
}

1 个答案:

答案 0 :(得分:1)

使用DependencyProperty中的常规Behavior代替附加的<Button Command="{Binding ContactCommand}"> <i:Interaction.Behaviors> <local:ContactCommandBehavior ResourceKey="blah"/> </i:Interaction.Behaviors> </Button> ,然后就可以了

OnAttached()

这是一个更好的语法。此外,请确保仅在{{1}}出现后才尝试读取这些属性的代码。