How to access another control's viewModel - c#

I have a CustomControl B, which uses a DataContext/MVVM (viewModelB). Now I want to bind one Property of my CustomControl to another control A (uses viewModelA as DataContext).
So I have two Ideas:
Whenever PropA in viewModelA changes, I could directly update PropB in the viewModelB. But this creates a dependency between the viewModels, which seems ugly to me. Or is this a common way in the MVVM pattern and can't be avoided?
As an alternative I could think of a dependency property on CustomControlB and wire it to CustomControlA's viewModel by a binding, something like that:
<myControlB PropB={Binding ElementName=myControlA, Path=DataContext.PropA} />.
So far so good, but the dependency property is defined on the view now. How should I visualize it?
a) Should I transfer the value (from the property wrapper) to viewModelB and bind to it from viewB's XAML code?
b) Or should I directly update the view from B's codeBehind? Would this be still a proper MVVM "style"?
Which of the options would you recommend?
regards
Andreas

As long as ViewModelA doesn't actively update ViewModelB, there is no real coupling between the two viewmodels. What I mean is that if your main view model (which knows both viewmodels) is the one that wires up the binding, the view models are still loosely coupled.
So to me any of these are fine:
Bind directly to myControlA.DataContext.PropA from XAML
Have the MainViewModel register for ViewModelA's property changed event and modify ViewModelB's property as necessary. Here MainViewModel knows about the two view models, but they know nothing of each other.

Related

WPF MVVM Change Model

I have a UserControl where the data gets passed in via a dependency property.
The UserControl is backed by a view model and the data is assigned to a property of the view model.
The XAML binds to both properties in the view model as well as properties within the passed in data.
The problem is if the user changes the data then databinding with the UI breaks. The UI is still bound to the original data object.
How can I cause the binding to get refreshed? INotifyPropertyChanged is implemented throughout, but it is not the property that is getting stale, but the binding. Basically, how do you go about replacing a backing model?
Since I'm not sure my description is clear I will try to describe it again in pseudo code.
<MyControl Source="{Binding Data}"/>
Where source is a dependency property of MyControl. In the PropertyChangedCallback this data is handed to the view model.
MyViewModel.Data = Source;
Within the MyControl XAML things are bound to this model.
{Binding Path=MyViewModel.Data.Item}
If you are wondering why the dependency property is defined in the UserControl, it is because it is a reusable control and the end user should not know about the view model.
"The UserControl is backed by a view model" and thus breaketh the application.
The UserControl's DataContext should be the Model. Period. If you need to perform UI logic, do it in the codebehind. Need something else? Create DependencyProperties on the surface of your UserControl to supply them.
When you create a ViewModel specifically for your UserControl, you break the natural flow of the DataContext (at this point, probably the Model the UC is designed to work with) and binding within the UserControl. It's pointless in most cases and harmful in some (as you have noticed).
My canonical answer on the subject contains more details.
Are you trying to swap-out the DataContext of the usercontrol during an application's session?
If you are, then I am fairly confident that this will not work.
Have you considered spinning up a new instance of that user control with the other DataConext?

MVVM in WPF how to communicate with the viewmodel

I guess I am still a little hazy on how communication goes in MVVM. I read that you are not supposed to use events to communicate with the viewmodel, so i assume that you send a command.
However, commands actually bubble up within the visual tree (the view), right? so then it may reach some target control that can handle the command. Does that target control then have a viewmodel that can modify the model?
Sorry, I'm really confused about how to get commands from the view to the model. I assume that getting information the other way is just a simple matter of having the model implement Inotifypropertychanged to tell the viewmodel that it has changed and then have the viewmodel implement inotifypropertychanged so that the view can bind to the viewmodel and have the properties update.
http://blogs.msdn.com/blogfiles/erwinvandervalk/WindowsLiveWriter/ImplementingtheModelViewViewModelpattern_D996/image_14.png
Not all commands bubble - those are RoutedUICommands, which are just a particular implementation of the ICommand interface provided by the framework. You can implement your own ICommand objects that have custom behavior and act just like normal objects (no bubbling, tunneling). If you create them in your ViewModel, certain View objects like Buttons and MenuItems can bind directly to them through their 'Command' properties.

MVVM: Convert code-behind to XAML

I've got an AllTopicsViewModel and its got a property ExerciseVM which is an AllExerciseViewModel, since I want to be able to refresh the AllExerciseViewModel of an ExerciseView so I am doing it like this (not even sure if it violates MVVM, pls. tell me). Well, I want to convert the 2 lines following the InitializeComponent to XAML but not sure how, can anyone help me out?
public MainWindow()
{
InitializeComponent();
AllTopicsViewModel vm = (AllTopicsViewModel)topicsView.DataContext;
vm.ExerciseVM = (AllExercisesViewModel)exercisesView.DataContext;
}
Yes, this is a misconception, according to the idea of MVVM.
Ideally, your View's codebehind (view.xaml.cs) contains nothing more than the auto generated code. Your view only accesses the ViewModel via WPF's data binding mechanisms. Because data binding via WPF is a loose coupling between the binding view and the bound-to ViewModel, you achieve the seperation that drives people to use MVVM.
You are retrieving the ViewModel in the Views codebehind from your control's DataContexts. With this, you create a strong reference between View and ViewModel. So, to help you with your question: You should think about what you are trying to to do with your ViewModel in the View's codebehind and how you can do it differently, either in the view's XAML or in the ViewModel's code itself.
If you like, post the complete MainWindow() class for some advice...
EDIT:
Ok, so its just about setting the child ViewModel on the parent ViewModel. The parent ViewModel AllTopicsViewModel should be responsible for setting its own ExerciseVM on initialization. This is not the View's job. the parent viewModel should assemble the data from one or more models and then create the child view models which the view consumes. Does that make sense for you?

Should ViewModel have pass-through DependencyProperties that bind to DependencyProperties on the Model?

I am new to WPF/MVVM and the examples I have found do not seem to cover an issue I am facing.
I have a screen for managing a rather complex business configuration object. In MVVM I think this means I should have the following:
A XAML View with close to zero logic
A ViewModel class that has the screen logic
My usual business classes fill the role of Model and have all business logic
In my situation there are business rules that say changes to fieldA of my business class might have various side effects, for example changing the value of fieldB, or populating an entire list of sub-objects.
I could be wrong, but I think I should keep these rules encapsulated in the business class, as these rules are not really about the screen so much as the entity.
Naturally, these side-effects need to make their way back onto the screen immediately.
So from the user's perspective, he might edit fieldA, and see fieldB updated on the View.
I understand how to databind from the View to the ViewModel.
But in my case, it seems that I need two layers of databinding: one between the View and ViewModel, and another between the ViewModel and the Model.
Given that I have essentially the same problem twice, I think one solution should apply. So I have made my Model class into a DependencyObject, and I have made its properties into DependencyProperties.
Looking at fieldA for example, it would appear in all three layers:
View as a visual component databound to ViewModel.FieldA, for example text="{Binding FieldA, Mode=TwoWay}"
ViewModel as a DependencyProperty bound "upward" to the View, and "downward" to the Model
Model as a DependencyProperty
I prefer not to directly couple my View XAML to the business object by skipping part #2, this does not seem like a clean application of the pattern to me. Perhaps that is misguided.
I essentially seem to need a "pass-through DependencyProperty" in my ViewModel.
My questions:
Is this the right general approach or am I thinking about it all wrong?
Are there examples out there using this pass-through approach?
Can someone give a code example of the proper way to create a pass-through binding between the ViewModel and Model FieldA DependencyProperties?
I struggled with this issue myself, and I imagine it is a very common snag when it comes to MVVM. My answer was to avoid polluting the domain with DependencyObject or INotifyPropertyChanged as it somewhat negates the validity of using a ViewModel.
The goal of a ViewModel is to expose a model in a manner that is relevant to a particular view. It gets confusing when the VM essentially needs to expose an entire domain object. I refer to these as "Editor" view models. These are the most tempting to pass through properties from the domain object. In these cases I give the VM a reference to a domain object (composition) and pass through getters and setters. The ViewModel adopts INotifyPropertyChanged and IDataErrorInfo rather than DependencyProperty to signal the UI if the UI needs to refresh or display validation errors. If the domain raises a validation error, then the VM catches it and prepares it into the data error info details for the view.
I would agree with Steve that you should avoid using DependencyObject and DependencyProperty in your model/domain classes, and the view model classes should adopt INotifyPropertyChanged and IDataErrorInfo for binding purposes.
I would add that in your view model classes, I would avoid using DependencyProperty except for properties that you need to utilize in xaml logic, such as DataTriggers.
For handling changes that are triggered within a model layer class, I would also have a reference to the model/domain object in the view model class, and pass through getters and setters to the model/domain class just as Steve mentioned. I would add that the model/domain class will need to raise an event that the view model class will need to subscribe to, so that OnPropertyChanged() for one or more properties can be called in your view model class based on a change that happened in your business logic.
Firstly, I would not recommend using dependency properties (DP) for view models, or models. DPs are properties that have been designed with UI concepts in mind, such as precedence rules, DataContext support, default values and more. You do not need these concepts within a view models, so you should use INotifyPropertyChanged instead.
Having a view-model that is simply a pass-through to a model layer adds no value at all. So don't do it! You should never add layers, structures or concepts to your code just because you think you should. Simplicity is something that you should always strive for.
So, if you can implement a model layer, with INotifyPropertyChanged simply bind that to your view.
However ... in some cases you may not be able to implement INotifyPropertyChanged in your model. It might be generated from a web service for example. In this case you will need a view model that performs pass-through functionality, but also adds change notification via INotifyPropertyChanged.

MVVM Binding with exposed property

I have a View that is hooked to a ViewModel. I have a singleton class that's exposed by foo.Current. I have a property on that class that will be changing as the result of a button click command calling a foo.Current function. I want to be able to bind a textbox's text to that value and when that value updates the textbox will update. My ViewModel does implement INotifyPropertyChanged and I have other properties on the view model that update controls fine. What is the best way I can make that singleton class update my ViewModel with the new value?
I'm thinking I need to figure out a way to make the Singleton class update the ViewModel.
There's no "best" way in current situation, options are as follows:
Define a property in your viewmodel and pass that viewmodel to your singleton. Singleton should change the relevant property along with it's own.
Move properties from singleton to viewmodel or include singleton in the viewmodel itself
Create an event for changing the property on the singleton
Inherit singleton from INotifyPropertyChanged and in your VM attach to PropertyChanged event of singleton. And monitor your property name.
...
Easiest one would be the first option though there might be some architectural inconsistencies in your app that should be treated.
If I understand you well, I would use Observer pattern.

Categories