How can I access a view property from my ViewModel?
I have a ViewModel whose properties are bounded to from the View (XAML file). I also have a property "StaticText" in the code behind file.
how can I access the property "StaticText" from inside the ViewModel ?
as suggested by Cameron, i've created a dependency property in my View :
String textToTest="I am just testing .";
public string TextToTest
{
get { return (string)this.GetValue(TextToTestProperty); }
set { 开发者_StackOverflowthis.SetValue(TextToTestProperty, value); }
}
public static readonly DependencyProperty TextToTestProperty =
DependencyProperty.Register("TextToTest", typeof(string),
typeof(MainWindow), new PropertyMetadata(false));
and I've added this to the constructor :
Binding aBinding = new Binding();
aBinding.Path = new PropertyPath("TextToTest");
aBinding.Source = viewModel;
aBinding.Mode = BindingMode.TwoWay;
this.SetBinding(TextToTestProperty, aBinding);
but I get an exception when I run the code.
By making the property a Dependency Property you can bind the property in the View to a property in the 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(""));
See How to: Implement a Dependency Property
精彩评论