2012-11-18 27 views
0

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

什么是修复?

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

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

你什么时候尝试访问它?你是否等到“已加载”事件发射? – Xcalibur37

回答

1

使用正DependencyPropertyBehavior而不是连接,以获得,那么你可以做

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

这是一个好得多的语法。此外,请确保仅在OnAttached()之后才会尝试读取这些属性的代码。

+0

* *在语法上更好,但我的值仍然为空。请在帖子末尾查看编辑后的代码! – Berryl

+0

把它整理出来 - 欢呼! – Berryl