2011-02-07 53 views
2

我有一個用戶控件我創建了一個名爲TextBoxAndMore,它包含一個文本框(稱爲textBox1),旁邊有一個「更多」按鈕。在這個用戶控件上,我有一個名爲Text的屬性。我想要這個Text屬性來鏡像文本框中的文本。在我的用戶控件綁定不起作用

我想這個屬性是可綁定,這樣在我的XAML,我可以把它綁定到名爲說明在我的ViewModel一個String屬性,像這樣:

<my:TextBoxAndMore Text="{Binding Path=Description}" /> 

所以我下面的代碼(由propdb片段生成):

// Using a DependencyProperty as the backing store for Text. This enables animation, styling, binding, etc... 
    public static readonly DependencyProperty TextProperty = 
     DependencyProperty.Register("Text", typeof(String), typeof(TextBoxAndMore), 
     new UIPropertyMetadata(String.Empty)); 

    public String Text 
    { 
     get { return (String)GetValue(TextProperty); } 
     set { SetValue(TextProperty, value); } 
    } 

而且,在文本框中,我有連接到TextChanged事件處理程序,其想法是這樣的代碼,當文本框中的用戶類型,該用戶的Text屬性控制隨之變化:

private void textBox1_TextChanged(object sender, TextChangedEventArgs e) 
    { 
     Text = textBox1.Text; 
    } 

但是,最終結果是綁定根本不起作用。在輸出窗口中沒有錯誤,並且我的ViewModel中的Description屬性沒有被設置(它仍然爲空)。

我確定這是顯而易見的,但我對WPF很陌生,並希望得到一些指導。

+1

相反,你想改變綁定爲「TwoWay」,以便用戶進行的更新自動返回到屬性。 – Gabe 2011-02-07 17:00:08

+0

謝謝,我已經將XAML更改爲``(這是你的意思嗎?),但我似乎仍然有同樣的問題。 – Matt 2011-02-07 17:04:54

回答

2

我認爲你需要配置2路結合:

<my:TextBoxAndMore Text="{Binding Path=Description Mode=TwoWay}" /> 

您也可以刪除TextChanged事件代碼的控制,還可以使用雙向綁定的控件的Text屬性。

編輯:

< - > ==雙向綁定...

TextBlockInControlsTemplate < - > TextDepPropInControl < - 一個`TextChanged`處理程序> DescriptionPropInVM