【问题标题】:Binding to a property in a UserControl绑定到 UserControl 中的属性
【发布时间】:2011-07-22 20:57:51
【问题描述】:

我有一个用户控件,我想在其中公开一个名为 ExpressionText 的属性,并在 xaml 可以为该属性定义一个绑定。 所以我创建了一个依赖属性

public static readonly DependencyProperty EditorText =DependencyProperty.Register("EditorText", typeof(string), typeof(MyUerControl));

和

public string ExpressionText 
{
    get
    {
        return (string)GetValue(EditorText);
    }
    set
    {
        SetValue(EditorText, value);
    }
}

在 xaml 中我这样做了。

     <controls:MyUerControl x:Name="textEditor" ExpressionText="{Binding 
                                  Path=Expression,Mode=TwoWay}" />

但我明白了

无法在 MyUserControl 类型的 ExpressionText 属性上设置绑定。可以设置绑定 仅在依赖对象类型错误的依赖属性上。

我的方法有问题吗?我该如何解决这个问题?

【问题讨论】:

    标签: c# wpf data-binding user-controls dependency-properties


    【解决方案1】:

    这应该可行:

    public static DependencyProperty EditorTextProperty = DependencyProperty.Register("ExpressionText", typeof(string), typeof(MyUserControl),
              new PropertyMetadata(new PropertyChangedCallback((s, e) =>
              { })));
    public string ExpressionText
    {
        get
        {
            return (string)base.GetValue(EditorTextProperty);
        }
        set
        {
            base.SetValue(EditorTextProperty, value);
        }
    }
    

    【讨论】:

    • 必须说我很惊讶我的回答被接受了:P Geoff 解释了你做错了什么,我只是在展示如何解决它:)
    【解决方案2】:

    您将 EditorText 定义为 DependencyProperty 的名称。这是您可以公开绑定到的名称。如果您希望它被称为 ExpressionText,那么您需要将其注册为名称。

       public static readonly DependencyProperty EditorText =
                               DependencyProperty.Register("ExpressionText", typeof(string), typeof(MyUerControl));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-30
      • 2015-04-18
      相关资源
      最近更新 更多