WPF usercontrol Twoway binding Dependency Property

后端 未结 2 1557
既然无缘
既然无缘 2020-12-05 19:33

I created a Dependency Property in the usercontrol, but however changes in the usercontrol was NOT notified to the Viewmodel

Usercontrol



        
相关标签:
2条回答
  • 2020-12-05 19:44

    Bind the TextBox.Text property in the UserControl to its SampleProperty like this:

    <TextBox Text="{Binding SampleProperty,
                    RelativeSource={RelativeSource AncestorType=UserControl}}"/>
    

    Now you could simply remove your OnSamplePropertyChanged callback.


    You might also register SampleProperty to bind two-way by default like this:

    public static readonly DependencyProperty
        SamplePropertyProperty = DependencyProperty.Register(
            "SampleProperty", typeof(string), typeof(UserControl1),
            new FrameworkPropertyMetadata(
                null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
    
    0 讨论(0)
  • 2020-12-05 19:58

    An alternative way to do this is an ElementName Binding. First assign the x:Name attribute to the UserControl (for example x:Name="MyUC"), then change the binding to:

    <TextBox Text="{Binding ElementName=MyUC, Path=SampleProperty}"/>
    
    0 讨论(0)
提交回复
热议问题