我有一個工作附加的行爲,我想添加一個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);
/////////////////////////////////
}
你什麼時候嘗試訪問它?你是否等到「已加載」事件發射? – Xcalibur37