2015-07-21 48 views
0

我試圖實現具有佔位符文本的自定義文本框。按照預期,我的模型的「名字」屬性的內容將顯示在文本框中。我遇到的問題是當我更改文本框的文本時,它不會在源模型中更新。這是爲什麼?usercontrol的數據綁定不會更新源模型

我試着將綁定模式設置爲「TwoWay」,但它沒有改變任何東西。有什麼我做錯了嗎?

編輯:傻逼我!事實證明,我必須在兩個綁定上放置Mode =「TwoWay」,而不僅僅是usercontrol。我會盡可能快地回答。

Model.cs

public class Student 
{ 
    public string FirstName { get; set; } 
} 

MainWindow.xaml

<grid> 
    <ui:prettyTextbox Text="{Binding FirstName}" PlaceholderText="#Enter your name"> 
</grid> 

PrettyTextbox.xaml

<UserControl x:Name="prettyTextbox"> 
    <Grid> 
     <TextBlock Text="{Binding Path=PlaceholderText, ElementName=prettyTextbox}" 
         Visibility="{Binding Path=Text, ElementName=prettyTextbox, Converter={StaticResource StringLengthToVisibilityConverter}}"/> 
     <TextBox Text="{Binding Path=Text, ElementName=prettyTextbox, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/> 
    </Grid> 
</UserControl> 

PrettyTextbox.xaml.cs

public partial class PrettyTextbox : INotifyPropertyChanged 
{ 
    public static readonly DependencyProperty PlaceholderTextProperty = 
      DependencyProperty.Register("PlaceholderText", typeof (string), 
             typeof(PrettyTextbox), new FrameworkPropertyMetadata(default(string))); 

    public string PlaceholderText 
    { 
     get { return (string)GetValue(PlaceholderTextProperty); } 
     set 
     { 
      SetValue(PlaceholderTextProperty, value); 
      OnPropertyChanged(); 
     } 
    } 


    public static readonly DependencyProperty TextProperty = 
     DependencyProperty.Register("Text", typeof(string), 
            typeof(PrettyTextbox), new FrameworkPropertyMetadata(default(string))); 

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

    public PrettyTextbox() 
    { 
     InitializeComponent(); 
    } 

} 

}

回答

0

你忘了讓text屬性綁定默認爲雙向,所以你需要改變這一部分:

<ui:prettyTextbox Text="{Binding FirstName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/> 

或更改文本屬性FrameworkPropertyMetadata到:

new FrameworkPropertyMetadata 
{ 
    DefaultValue = null, 
    BindsTwoWayByDefault = true 
}