我想将自定义控件的依赖项属性绑定到其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的文本属性。
任何有关这方面的帮助,非常感谢。
显示您正在使用的xaml绑定。 –
它似乎好像这应该工作,把一个断点在文本 Setter –
@eranotzer:我曾尝试在文本设置器上放置一个断点,但它从不触及视图中的setter,原因是属性没有绑定到底层viewmodels属性。 – KSingh