【问题标题】:Custom Control DataBinding wpf自定义控件数据绑定 wpf
【发布时间】:2015-07-07 03:31:03
【问题描述】:

目前正在实现一个自定义控件,我想直接从我的 viewModel 绑定一些值,而不使用 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);

       }
   }

非常感谢您的帮助

【问题讨论】:

  • 您正在将文本绑定到 double 类型的属性并指定双向绑定。 ToString() 将发生双精度字符串,但您不能自动转换回来。这篇文章有一些关于转换的细节:stackoverflow.com/questions/17178738/…

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


【解决方案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>

如果您这样做,您可以轻松地在任何视图中使用此用户控件,例如:

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

【讨论】:

  • 非常感谢。让我的控件继承自 UserControl 而不是 Control 并更改绑定解决了一切。
  • 好的,我会做的:-)。但我还有更多问题请教:在资源字典中为此控件使用样式模板的 xaml 是什么?
  • 我不明白你想要什么,也许你应该创建一个包含更多信息的新问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-06-14
  • 1970-01-01
  • 2015-06-03
  • 1970-01-01
  • 2013-03-15
  • 1970-01-01
  • 2011-08-06
相关资源
最近更新 更多