我有一个工作附加行为,我想添加一个 DP。我可以在 XAML 中设置该属性,但当我尝试访问它时它为空。
解决方法是什么?
干杯,
贝里尔
xml
<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);
/////////////////////////////////
}