绑定到用户控件中的属性

问题描述:

我有一个用户控件,我想在其中公开一个名为ExpressionText的属性,并在 xaml中绑定可以定义到此属性。 所以我在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); 
    } 
} 

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

,但我得到

绑定不能在类型的MyUserControl的ExpressionText属性设置。绑定只能在依赖对象类型错误类型的依赖属性上设置为 。

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

这应该工作:

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

必须说,我很惊讶,我的回答是公认的:P杰夫解释你做错了什么,我只显示如何解决它:) – 2011-03-26 12:33:21

您正在将EditorText定义为您的DependencyProperty的名称。这是公开可供您绑定的名称。如果你想要它被称为ExpressionText,那么你需要注册该名称。

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