简体   繁体   中英

UserControl with Dependency property

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.

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;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM