0

DP を追加したい動作中の動作があります。XAML でプロパティを設定できますが、アクセスしようとすると null になります。

修正は何ですか?

乾杯、
ベリル

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

1 に答える 1

1

DependencyProperty付属のものの代わりに通常のものを使用するBehaviorと、次のことができます

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

これははるかに優れた構文です。また、これらのプロパティを読み取ろうとするコードが発生した後にのみ確認してOnAttached()ください。

于 2012-11-18T15:39:31.517 に答える