问题
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