Set property on ViewModel from View
What do I need to add to set a public property on my ViewModel instance from my View? I'd like to set some properties on the ViewModel resource rather than bind it from some element in my view.
View XAML:
<UserControl.Resources>
<vm:MainViewModel x:Key="mainViewModel" MyProperty="30" />
</UserControl.Resources>
<UserControl.DataContext>
<Binding Source={StaticResource mainViewModel}" />
</UserControl.DataContext>
MainViewModel.cs (implements INotifyPropertyChanged)
private int _myProperty;
public int MyProperty{
get { return _myProperty; }
set
{
_myProperty = value;
OnPropertyChanged("MyProperty");
}
}
The setter on MyProperty is never called. There must be some fundamental MVVM thing i'm doing wrong开发者_开发问答.
Normally you would create a binding which binds the property on the ViewModel with a property of a control. For example you could bind MyProperty to a textbox like so:
<TextBox Text="{Binding MyProperty}" />
Since the parent data context specified by UserControl.DataContext is an instance of MainViewModel, this binding will bind to a property of that object.
Well what you can do is set the MouseDown of a control such as a 'save' button on a method of the code-behind of your view. Then in the codebehind, you set your ViewModel's property or call his method.
In your View.xaml.cs you need something like this
private MyViewModele myVM;
public MyView()
{
InitializeComponent();
Loaded += new RoutedEventHandler(Initialized); //After loading, call Initialized(...)
}
private void Initialized(object sender, RoutedEventArgs e)
{
myVM= this.DataContext as MyViewModele ; //Reference to your ViewModel
}
private void Label_General(object sender, RoutedEventArgs e)
{
myVM.Property = "w/e"; //Set the ViewModel property
}
In your View.xaml
<Label
Content="Click this label"
MouseDown="Label_General"
>
</Label>
Here i setted the Property to a static string but you can retrive any of your View's control and use its value to push it in your ViewModel.
I hope this answer your question.
My psuedo code above actually works. I had another issue with my ViewModel's constructor which had me stumped.
精彩评论