Custom Control DataBinding wpf

淺唱寂寞╮ 提交于 2019-12-02 05:54:08

问题


Currently implementing a custom control I would like to bind some Value directly from my viewModel without using xaml. I can do this:

<customControls:MyControl MyValue="{Binding ElementName=MyElem, Path=Text}">
<Textbox Text="{Binding Mytext}" />

But not:

<customControls:MyControl MyValue="{Binding MyText}">

The controls is defined in a template and inside the Control code my the MyProperty is defined as:

   public static readonly DependencyProperty MyValueProperty = DependencyProperty.Register("MyValue", typeof(double), typeof(CustomOEE), new FrameworkPropertyMetadata((Double)20,FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
   public double MyValue
   {
       get
       {
           return (double)GetValue(MyValueProperty);
       }
       set
       {
           SetValue(MyValueProperty, value);

       }
   }

Thanks a lot for your help


回答1:


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}"/>


来源:https://stackoverflow.com/questions/29916756/custom-control-databinding-wpf

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