自定义控件数据绑定wpf

自定义控件数据绑定wpf,wpf,wpf-controls,custom-controls,dependency-properties,Wpf,Wpf Controls,Custom Controls,Dependency Properties,目前正在实现一个自定义控件,我想直接从viewModel绑定一些值,而不使用xaml。 我可以这样做: <customControls:MyControl MyValue="{Binding ElementName=MyElem, Path=Text}"> <Textbox Text="{Binding Mytext}" /> 非常感谢您的帮助作为一个一般性的回答,在UserControl中,您只绑定到UserControl DependencyProperties,并

目前正在实现一个自定义控件,我想直接从viewModel绑定一些值,而不使用xaml。 我可以这样做:

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

非常感谢您的帮助

作为一个一般性的回答,在UserControl中,您只绑定到UserControl DependencyProperties,并使用ElementName或RelativeSource绑定来实现这一点,并且您永远不应该在UserControl中设置DataContext

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,如:

<myControls:MyUserControl MyOwnDPIDeclaredInMyUc="{Binding MyPropertyInMyViewmodel}"/>


将文本绑定到double类型的属性并指定双向绑定。ToString()将出现双精度转换字符串,但无法自动转换回。这篇文章有一些关于转换的细节:非常感谢。使我的控件继承自UserControl而非control,并更改绑定解决了所有问题。好的,我将这样做:-)。但我还有一个问题,请问:在ressource dictionnary中,这个控件使用样式模板的xaml是什么?我不明白您想要什么,也许您应该创建一个包含更多信息的新问题
public static readonly DependencyProperty MyOwnDPIDeclaredInMyUcProperty = 
    DependencyProperty.Register("MyOwnDPIDeclaredInMyUc", 
         typeof(string), typeof(MyUserControl));

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

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