簡體   English   中英

綁定到UserControl中的屬性

[英]Binding to a property in a UserControl

我有一個usercontrol,我想在其中公開一個名為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屬性上設置綁定。 綁定只能在Dependency對象錯誤類型的depenedecy屬性上設置。

我的方法有問題嗎? 我該如何解決這個問題?

您正在將EditorText定義為DependencyProperty的名稱。 這是公開可供您綁定的名稱。 如果您希望將其稱為ExpressionText,則需要將其注冊為名稱。

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

這應該工作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM