2
votes

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
You are binding text to a property of type double and specifying two-way binding. Double to string will happen with ToString() but you can't automatically convert back. This post has some details on the conversion: stackoverflow.com/questions/17178738/… - James Lucas

1 Answers

2
votes

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