UserControl中的TwoWay DataBinding

时间:2016-04-26 14:50:11

标签: c# wpf binding

我有一个UserControl。它包含一个带有Adorner的文本框(为简洁起见而删除)

<UserControl x:Class="Test.UserControlBindings"         
         DataContext="{Binding Mode=OneWay, RelativeSource={RelativeSource Self}}"
         mc:Ignorable="d" KeyboardNavigation.TabNavigation="Cycle" x:Name="Control"
         d:DesignHeight="300" d:DesignWidth="300"  >
    <AdornerDecorator>
        <TextBox x:Name="InputTextBox" VerticalContentAlignment="Center" Text="{Binding Text, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" FontSize="{Binding ElementName=Control, Path=FontSize}"/>
    </AdornerDecorator>
</UserControl>

我将它绑定到&#34; Text&#34;用户控件

public partial class WatermarkTextBox : INotifyPropertyChanged {
    private static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(WatermarkTextBox), new FrameworkPropertyMetadata(default(string), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));

    public WatermarkTextBox() {
        this.InitializeComponent();
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public string Text {
        get {
            return (string)GetValue(TextProperty);
        }

        set {
            this.SetValue(TextProperty, value);
            OnPropertyChanged("Text");
        }
    }

    [NotifyPropertyChangedInvocator]
    protected virtual void OnPropertyChanged(string propertyName = null) {
        PropertyChangedEventHandler handler = this.PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }

从未调用过Setter。因此,当我绑定到此用户控件时,绑定永远不会更新。我该怎么做才能修复绑定?

1 个答案:

答案 0 :(得分:1)

绑定不使用getter和setter,它们直接使用GetValue和SetValue。您也不需要实现INotifyPropertyChanged。 要指定更改处理程序,请将其包含在元数据定义中,如下所示:

public static readonly DependencyProperty TextProperty = DependencyProperty.Register(
    "Text", typeof(string), typeof(WatermarkTextBox),
    new FrameworkPropertyMetadata(default(string), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
        (s, e) => ((WatermarkTextBox)s).OnTextChanged((string)e.OldValue, (string)e.NewValue))
);

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

void OnTextChanged(string oldValue, string newValue) { 
    //....
}