views:

52

answers:

1

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 { this.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.

+3  A: 

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

Cameron MacFarland
I can't figure it out. I created a dependency property in the code behind of the V as suggested by Cameron. and in the View constructor, I created a binding as such : Binding aBinding = new Binding(); aBinding.Path = new PropertyPath("TextToTest"); aBinding.Source = _vm; this.SetBinding(TextToTestProperty, aBinding); but i get an exception when i run my code
Attilah