0

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

解决方法是什么?

干杯,
贝里尔

xml

<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 并使属性非静态。当我尝试获取它时,该值仍然为空

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);
    /////////////////////////////////
}
4

1 回答 1

1

DependencyPropertyBehavior而不是附加的中使用常规,然后你可以做

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

这是一个更好的语法。此外,请确保您尝试读取这些属性的代码仅在发生之后OnAttached()

于 2012-11-18T15:39:31.517 回答