【问题标题】:How can i change dependency property value inside a usercontrol?如何更改用户控件内的依赖属性值?
【发布时间】:2016-01-19 07:23:24
【问题描述】:

我有具有 TextInUserControl 属性的用户控件。

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

我可以在我的主窗口中绑定到这个属性,当我在我的主窗口中更改这个属性时,它也会在用户控件中更新。这意味着正在完美读取来自源的属性更改。但是如何更改主窗口的此属性以在用户控件内部(到源)?

我正在尝试做但没有工作的示例:

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

【问题讨论】:

    标签: c# wpf xaml data-binding user-controls


    【解决方案1】:

    如果要初始化文本,可以在依赖属性的默认值中进行。您可以编写属性元数据,构造函数的第一个参数是默认属性值。参考下面的代码。

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

    【讨论】:

    • 感谢您的快速回复。但我不仅想初始化它,而且希望能够改变它。真实情况是我有一个验证码框用户控件,当用户输入正确的验证码时,IsValidated bool 变为“真”。我想使用这个 IsValidated 作为依赖属性来在我的主窗口中获取它。我只是想通过将 bool 绑定到控件来检查我的主窗口(登录窗口)中控件的 IsValidated 属性。所以我的主窗口永远不应该更改属性,而只能读取它(单向绑定),但似乎我无法在我的用户控件中更新 IsValidated。
    • 我已经编辑了我的答案。您可以使用 SetValue 方法设置值。
    • +1。我不知道为什么人们会问一些问题,得到一个可行的解决方案(他们承认),就是这样。
    猜你喜欢
    • 1970-01-01
    • 2021-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-07
    • 1970-01-01
    • 2018-05-20
    • 1970-01-01
    相关资源
    最近更新 更多