2015-10-20 69 views
-1

我有用戶控件具有TextInUserControl屬性。如何更改usercontrol內的依賴項屬性值?

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

我可以綁定到這個屬性在我的主窗口,當我在我的主窗口更改此屬性,它在用戶控件太更新。這意味着來自源的財產變化正在被完美地讀取。但是,我怎麼能改變這個屬性爲mainwindow帶來(來源),在用戶控制內?什麼我想這樣做,但沒有工作

例子:

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

回答

0

如果你想初始化你能做到這一點的依賴項屬性的默認值的文本。您可以編寫屬性元數據,並且構造函數的第一個參數是默認屬性值。請參閱以下代碼。

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

感謝您的快速響應。但我不僅想要初始化它,而且希望能夠改變它。真實情況是我有一個驗證碼框用戶控件,當用戶輸入正確的驗證碼時,IsValidated布爾變成「true」。我想使用這個IsValidated作爲依賴屬性來獲取它在我的主窗口中。我只是想通過將bool綁定到控件來在我的主窗口(登錄窗口)中檢查我的控件的IsValidated屬性。所以我的主窗口不應該改變屬性,但只能讀取它(單向綁定),但似乎我不能更新我的用戶控件內的IsValidated。 –

+0

我編輯了我的答案。您可以使用SetValue方法設置該值。 –

+0

謝謝Ayappan,你說得對,SetValue命令有效。 –