简体   繁体   中英

How can i change dependency property value inside a usercontrol?

I have user control that has TextInUserControl property.

UserControl1.cs

    public static readonly DependencyProperty TextInUserControlProperty =
        DependencyProperty.Register("TextInUserControl",
            typeof(string),
            typeof(UserControl1));

    public string TextInUserControl
    {
        get { return (string)GetValue(TextInUserControlProperty); }
        set { SetValue(TextInUserControlProperty, value); }
    }

I can bind to this property in my mainwindow, and when I change this property in my mainwindow, it updates in usercontrol too. It means that property changes from source is being read perfectly. But how can I change this property for mainwindow to bring (to source), inside the user control?

Example of what I'm trying to do but not working:

    public UserControl1()
    {
        InitializeComponent();
        TextInUserControl = "test";
        //or something like SetValue(TextInUserControlProperty, "test");
    }

If you want to initialize the text you can do it in the default value of the dependency property. You can write property metadata and the first parameter of the constructor is the default property value. Refer below code.

 public partial class UserControl1 : UserControl
{  
    public static readonly DependencyProperty TextInUserControlProperty =
    DependencyProperty.Register("TextInUserControl",
        typeof(string),
        typeof(UserControl1));

    public string TextInUserControl
    {
        get { return (string)GetValue(TextInUserControlProperty); }
        set { SetValue(TextInUserControlProperty, value); }
    }

    public UserControl1()
    {
        InitializeComponent();           

        this.SetValue(UserControl1.TextInUserControlProperty, "My Text");
    }
}

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