Reputation: 15237
I'm still trying to wrap my head around some of the finer points of using WPF and MVVM. One thing that has bugged me for a while is how to get values from the View into the ViewModel. Let me explain the scenario.
I have a Window with several UserControls inside. One of those UserControls has a DependencyProperty
of type TimeSpan
named CurrentTime
. It is bound (in the XAML for the window) to the Window's ViewModel.
Now, I also have a ViewModel for the UserControl. It needs access to the CurrentTime property in order to create objects based off it. How do I get that value into my ViewModel? I see a couple of options:
Am I missing any other options? Which of the above (or ones I missed) is the best way to do this?
I read through this thread here on SO, because it was similar, but the answers didn't really answer my question - I would love to do it with bindings or commands or something, but I just can't figure out how exactly.
Upvotes: 2
Views: 1329
Reputation: 20756
The third option is the way to go here, but you'll have to specify binding in the code-behind of your UserControl
:
public partial class MyUserControl : UserControl
{
public MyUserControl() {
InitializeComponent();
SetBinding(MyPropertyProperty,
new Binding {Path = new PropertyPath("MyViewModelProperty"), Mode = BindingMode.OneWayToSource});
}
}
Upvotes: 4