自定义控件数据绑定wpf [英] Custom Control DataBinding wpf

查看:341
本文介绍了自定义控件数据绑定wpf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

但不是:

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

控件在模板中定义,并且在MyProperty的控件代码中定义为:

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

       }
   }

非常感谢您的帮助

推荐答案

作为一个普遍的答案,在UserControl中,您仅绑定到UserControl DependencyProperties,并使用ElementName或RelativeSource绑定来完成,应该从不在UserControl中设置DataContext。

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

这篇关于自定义控件数据绑定wpf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆