I have a working attached behavior which I would like to add a DP to. I can set the property in XAML but it is null when I try to access it.
What is the fix?
Cheers,
Berryl
<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);
//************
....
}
}
I change the code as follows, changing RegisterAttached to Register and making the property non-static. The value is still null when I try to get at it though
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);
/////////////////////////////////
}
Use a regular DependencyProperty
in the Behavior
instead of an attached one, then you can do
<Button Command="{Binding ContactCommand}">
<i:Interaction.Behaviors>
<local:ContactCommandBehavior ResourceKey="blah"/>
</i:Interaction.Behaviors>
</Button>
which is a much nicer syntax. Also, make sure the code you try to read these properties only AFTER OnAttached()
has ocurred.