自定义控件DataBinding wpf

时间:2015-04-28 10:22:29

标签: wpf wpf-controls custom-controls dependency-properties

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

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

但不是:

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

控件在模板中定义,在控制代码中我的MyProperty定义为:

   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);

       }
   }

非常感谢你的帮助

1 个答案:

答案 0 :(得分:1)

作为一般答案,在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 x:Name="myRealUC" x:class="MyUserControl">
   <TextBox Text="{Binding ElementName=myRealUC, Path=MyOwnDPIDeclaredInMyUc, Mode=TwoWay}"/>
 <UserControl>

如果您这样做,您可以在任何视图中轻松使用此Usercontrol,如:

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