2012-11-18 29 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