Wpf 依赖属性用法

Wpf 依赖属性用法,wpf,xaml,dependency-properties,attached-properties,Wpf,Xaml,Dependency Properties,Attached Properties,我有一个工作附加行为,我想添加一个DP。我可以在XAML中设置该属性,但当我尝试访问它时,它是空的 解决办法是什么 干杯, 贝里尔 xaml 在行为中使用常规的DependencyProperty,而不是附加属性,然后您可以执行以下操作 <Button Command="{Binding ContactCommand}"> <i:Interaction.Behaviors> <local:ContactCommandBehavior Reso

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

解决办法是什么

干杯,
贝里尔

xaml
行为
中使用常规的
DependencyProperty
,而不是附加属性,然后您可以执行以下操作

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


这是一个更好的语法。另外,请确保您尝试读取这些属性的代码只有在出现
onatached()
之后才能读取。

您何时尝试访问它?你会等到“Loaded”事件被触发吗?这在语法上更好,但我的值仍然是空的。请参见文章末尾的编辑代码!
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);
    /////////////////////////////////
}
<Button Command="{Binding ContactCommand}">
    <i:Interaction.Behaviors>
        <local:ContactCommandBehavior ResourceKey="blah"/>
    </i:Interaction.Behaviors>
</Button>