wpf - 自定义控件数据绑定(bind) wpf

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

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

       }
   }

非常感谢您的帮助

最佳答案

作为一般答案,在 UserControl 中,您仅绑定(bind)到 UserControl DependencyProperties,并使用 ElementName 或relativeSource 绑定(bind)来执行此操作,并且您不应该永远在 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>

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

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

关于wpf - 自定义控件数据绑定(bind) wpf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29916756/

相关文章:

c# - WPF 鼠标按下事件

wpf - 如何手动触发 MahApps 动画

基于XSD的WPF表单

c# 和日期选择器,如何更改格式?

ios - 如何在 Interface Builder 中使用自定义 UIButton?

c++ - 将 .NET WPF 应用程序重写为 C++ 的最佳 GUI 工具包是什么?

c# - 如何使用自定义 WPF 控件上的依赖属性处理计算值

wpf - 在wpf中设置格式化文本的上标和下标

wpf - 防止 ControlTemplate 中的控件继承全局样式 (WPF)

c# - FindName 在 TabItem 上失败