简体   繁体   English

UserControl中的双向数据绑定

[英]TwoWay DataBinding in a UserControl

I have a UserControl. 我有一个UserControl。 It Contains a single textbox with an Adorner (removed for brevity) 它包含一个带有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>

I'm binding it to "Text" of the UserControl 我将其绑定到UserControl的“文本”

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

The Setter is never being called. 塞特永远不会被调用。 So when I bind to this user control, the bindings are never updated. 因此,当我绑定到此用户控件时,绑定永远不会更新。 What can I do to fix the binding? 我该如何解决绑定问题?

Bindings don't use the getters and setters, they use GetValue and SetValue directly. 绑定不使用getter和setter,而是直接使用GetValue和SetValue。 You also don't need to implement INotifyPropertyChanged. 您也不需要实现INotifyPropertyChanged。 In order to specify a change handler, include it in your metadata definition like this: 为了指定变更处理程序,请将其包含在您的元数据定义中,如下所示:

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) { 
    //....
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM