我有一个ViewModel,其属性是从View(XAML文件)绑定的。 我在代码隐藏文件中也有一个属性“StaticText”。
如何从ViewModel内部访问“StaticText”属性?
根据Cameron的建议,我在我的视图中创建了一个依赖属性:
String textToTest="I am just testing .";
public string TextToTest
{
get { return (string)this.GetValue(TextToTestProperty); }
set { this.SetValue(TextToTestProperty, value); }
}
public static readonly DependencyProperty TextToTestProperty =
DependencyProperty.Register("TextToTest", typeof(string),
typeof(MainWindow), new PropertyMetadata(false));
我已将此添加到构造函数中:
Binding aBinding = new Binding();
aBinding.Path = new PropertyPath("TextToTest");
aBinding.Source = viewModel;
aBinding.Mode = BindingMode.TwoWay;
this.SetBinding(TextToTestProperty, aBinding);
但是当我运行代码时出现异常。
答案 0 :(得分:3)
通过使属性为Dependency Property,您可以将View中的属性绑定到ViewModel中的属性。
public string TextToTest
{
get { return (string)this.GetValue(TextToTestProperty); }
set { this.SetValue(TextToTestProperty, value); }
}
public static readonly DependencyProperty TextToTestProperty =
DependencyProperty.Register("TextToTest", typeof(string),
typeof(MyControl), new PropertyMetadata(""));