依赖项属性使用情况



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

修复是什么?

干杯
贝瑞尔

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

为高核心编辑。

我按如下方式更改代码,将寄存器附加到寄存器并使属性非静态。不过,当我尝试获取它时,该值仍然为空

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

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

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

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

最新更新