2012-10-05 46 views
0

我想将自定义控件的依赖项属性绑定到其ViewModel属性。如何将自定义控件的依赖项属性绑定到其视图模型属性

自定义控件的样子:


public partial class MyCustomControl : Canvas 
    { 
      //Dependency Property 
      public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(MyCustomControl)); 


      private VisualCollection controls; 
      private TextBox textBox; 

      public string Text 
      { 
       get { return textBox.Text; } 
       set 
       { 
        SetValue(TextProperty, value); 
        textBox.Text = value; 
       } 
      } 

      //Constructor 
      public MyCustomControl() 
      { 
       controls = new VisualCollection(this); 
       InitializeComponent(); 

       textBox = new TextBox(); 
       textBox.ToolTip = "Start typing a value."; 

       controls.Add(textBox); 

       //Bind the property 
       this.SetBinding(TextProperty, new Binding("Text") {Mode = BindingMode.TwoWay, Source = DataContext}); 
      } 
    } 

和视图模式是这样的:


------- 

public class MyCustomControlViewModel: ObservableObject 
{ 
    private string _text; 


    public string Text 
    { 
     get { return _text; } 
     set { _text = value; RaisePropertyChanged("Text");} 
    } 
} 

---------- 

这约束力的 “文本” 属性不工作因为某些原因。

我想要做的是,在实际的实现中,我希望MyCustom控件的文本属性更新,当我更新我的基础ViewModel的文本属性。

任何有关这方面的帮助,非常感谢。

+0

显示您正在使用的xaml绑定。 –

+0

它似乎好像这应该工作,把一个断点在文本 Setter –

+0

@eranotzer:我曾尝试在文本设置器上放置一个断点,但它从不触及视图中的setter,原因是属性没有绑定到底层viewmodels属性。 – KSingh

回答

0

只需绑定到依赖属性

<MyCustomControl Text="{Binding Path=Text}" /> 
+0

我想将数据上下文绑定到基础视图模型,然后我期望我的控件属性绑定起作用。就像这样:' – KSingh

0

您应该将文本框成员绑定到你的TextProperty代替。我非常肯定你的Text属性在xaml中的绑定覆盖了你在构造函数中的绑定。

1

经过一番研究,我终于找出了我的代码问题。我通过创建一个静态事件处理程序来实现此代码,该处理程序实际将新属性值设置为依赖项属性的基础公共成员。依赖属性的声明是这样的:

//Dependency Property 
public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(MyCustomControl), new PropertyMetadata(null, OnTextChanged)); 

,然后定义设置的属性是一样的静态方法:

private static void OnTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) 
{ 
    MyCustomControl myCustomControl = (MyCustomControl)d; 
    myCustomControl.Text = (string) e.NewValue; 
} 

这是我唯一缺少的东西。

Cheers

相关问题