Custom Control DataBinding wpf

痴心易碎 提交于 2019-12-02 01:27:27
blindmeis

As a general answer, within a UserControl you bind just to the UserControl DependencyProperties and you do that with ElementName or RelativeSource binding and you should never set the DataContext within a UserControl.

public static readonly DependencyProperty MyOwnDPIDeclaredInMyUcProperty = 
    DependencyProperty.Register("MyOwnDPIDeclaredInMyUc", 
         typeof(string), typeof(MyUserControl));

public string MyOwnDPIDeclaredInMyUc
{
   get
   {
       return (string)GetValue(MyOwnDPIDeclaredInMyUcProperty);
   }
   set
   {
       SetValue(MyOwnDPIDeclaredInMyUcProperty, value);

   }
}

xaml

 <UserControl x:Name="myRealUC" x:class="MyUserControl">
   <TextBox Text="{Binding ElementName=myRealUC, Path=MyOwnDPIDeclaredInMyUc, Mode=TwoWay}"/>
 <UserControl>

If you do that you can easily use this Usercontrol in any view like:

<myControls:MyUserControl MyOwnDPIDeclaredInMyUc="{Binding MyPropertyInMyViewmodel}"/>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!