开发者

Binding to a property in a UserControl

I have a usercontrol in which i want to expose a property called ExpressionText and in the xaml a binding can be defined to this property. So i created a dependency property

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

and

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

in the xaml i do this.

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

but i get

A binding cannot be set on ExpressionText property of type MyUserControl. Binding can be set only on a depenedecy property of type Dependen开发者_运维知识库cy object error.

Is there something wrong in my approach ? How do i solve this problem ?


This should work:

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


You are defining EditorText as the name of your DependencyProperty. That is the name that is available publicly for you to bind to. If you want it to be called ExpressionText, then you need to register that as the name.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜