Reputation: 636
I created a UserControl class called TagItem, which currently consists of only one Button called mainButton.
It has a dependency property called DisplayedTag, which is type of Tag(a simple class containing data about my tags). My goal is that when the user sets DisplayedTag from XAML mainButton's text should be updated to Tag's TagName.
The code in TagItem:
public Tag DisplayedTag
{
get { return (Tag)GetValue(DisplayedTagProperty); }
set
{
SetValue(DisplayedTagProperty, value);
}
}
// Using a DependencyProperty as the backing store for MyProperty.
// This enables animation, styling, binding, etc...
public static DependencyProperty DisplayedTagProperty =
DependencyProperty.Register("DisplayedTag",
typeof(Tag),
typeof(TagItem),
new PropertyMetadata(new Tag(),
OnDisplayedTagPropertyChanged));
private static void OnDisplayedTagPropertyChanged(DependencyObject source,
DependencyPropertyChangedEventArgs e)
{
// Put some update logic here...
Tag tag = (Tag)e.NewValue;
mainButton.Content = tag.TagName;
}
In XAML:
<local:TagItem DisplayedTag="{Binding}"/>
This does not work because OnDisplayedTagPropertyChanged is static, while mainButton is not. I might be on a completely wrong track here, and would really appreciate some directions on solving the simple looking problem.
Upvotes: 0
Views: 66
Reputation: 5797
In the source
parameter of your OnDisplayedTagPropertyChanged
callback you get your UserControl derived control. You just have to cast it so you can access its member mainButton
.
I took any name for your class (don't know if everything is correct):
private static void OnDisplayedTagPropertyChanged(DependencyObject source,
DependencyPropertyChangedEventArgs e)
{
MyUserControl ctrl = source as MyUserControl;
if(ctrl == null) // should not happen
return;
Button b = ctrl.mainButton;
Tag tag = (Tag)e.NewValue;
mainButton.Content = tag.TagName;
}
Upvotes: 2