我有一个工作附加的行为,我想添加一个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