如何从我的ViewModel访问视图属性?
问题描述:
我有一个ViewModel的属性是从视图(XAML文件)有界。 我在代码后面的文件中也有一个属性“StaticText”。如何从我的ViewModel访问视图属性?
如何从ViewModel内部访问属性“StaticText”?
卡梅伦的建议,我创建了一个依赖属性在我看来:
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);
,但我得到一个异常时,我运行代码。
答
通过使属性为Dependency Property,您可以将视图中的属性绑定到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(""));
+0
我无法弄清楚。我在Cameron建议的V后面的代码中创建了一个依赖项属性。并在View构造函数中,我创建了一个绑定,如下所示:Binding aBinding = new Binding(); aBinding.Path = new PropertyPath(“TextToTest”); aBinding.Source = _vm; this.SetBinding(TextToTestProperty,aBinding);但是当我运行我的代码时我得到一个异常 – Attilah 2010-09-21 01:53:18
你**不要**直接访问从视图模型视图属性 - 虚拟机是不应该知道的V.使用依赖属性的组合通过@Cameron的建议和双向绑定。 – slugster 2010-09-21 00:32:11
@Slugster,我找不出来。我在Cameron建议的V后面的代码中创建了一个依赖项属性。并在View构造函数中,我创建了一个绑定,如下所示:Binding aBinding = new Binding(); aBinding.Path = new PropertyPath(“TextToTest”); aBinding.Source = _vm; this.SetBinding(TextToTestProperty,aBinding); this.SetBinding(TextToTestProperty,aBinding);但是当我运行我的代码时我得到一个异常。 – Attilah 2010-09-21 00:36:04
异常是因为您将属性元数据设置为缺省值为'false',而该值不能转换为字符串。我不喜欢从MSDN复制示例。 – 2010-09-21 04:54:46