简体   繁体   English

如何更改用户控件内的依赖属性值?

[英]How can i change dependency property value inside a usercontrol?

I have user control that has TextInUserControl property.我有具有 TextInUserControl 属性的用户控件。

UserControl1.cs用户控件1.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?但是如何更改 mainwindow 的此属性以在用户控件中引入(到源)?

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");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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