How to implement two-way binding on a property?

前端 未结 2 1234
野性不改
野性不改 2020-12-22 06:16

I know there are lots of questions about dependency properties, and I have looked at many of them, but none of them seems to solve my problem.

I have a Window like t

相关标签:
2条回答
  • Remove the assignment

    DataContext="{Binding RelativeSource={RelativeSource Self}}"
    

    from the UserControl's XAML. Instead, set the RelativeSource of the "internal" binding to the control instance:

    <UserControl x:Class="WpfBindingTest.TextInputWrapper" ...>
        <TextBox Text="{Binding MyText,
                        RelativeSource={RelativeSource AncestorType=UserControl}}"/>
    </UserControl>
    

    Explicitly setting the DataContext of a UserControl prevents inheriting the DataContext from its parent control, i.e. a Binding like

    <local:TextInputWrapper MyText="{Binding MyTextValue, Mode=TwoWay}" />
    

    would use the UserControl as source object, instead of the current DataContext.


    As a general rule, never explicitly set the DataContext of a UserControl.

    0 讨论(0)
  • 2020-12-22 06:41

    Try changing this line:

    public static readonly DependencyProperty MyTextProperty = DependencyProperty.Register("MyText",
    typeof(string), typeof(TextInputWrapper), new PropertyMetadata("Empty"));
    

    To this:

    public static readonly DependencyProperty MyTextProperty = DependencyProperty.Register("MyText",
        typeof(string), typeof(TextInputWrapper), new FrameworkPropertyMetadata("Empty", FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
    
    0 讨论(0)
提交回复
热议问题