Based on my previous question Accessing variables from XAML and object from ViewModel using Code Behind:
How would I know which executes first?
Is it the code behind or the ViewModel?
I just want to make sure that my code behind executes prior the ViewModel
The View and the ViewModel are both regular classes that get instantiated. This is done by calling the constructor as in any other class. So, as a simple answer to your question: Set a breakpoint in each constructor and see which one gets hit first.
There is no general answer to your question because it depends on your architecture and use case. Often, some control is bound to a property of the ViewModel of it's parent, which changes at some point. At that point your View already exists and you have no idea how long the value to which the property has been set is existing already. In other cases, your View is created for a specific ViewModel and takes it as constructor parameter.
The one way to make sure that the ViewModel exists before the View is to pass the ViewModel as a constructor parameter. The idea behind constructor parameters is to express: "This class needs existing instances of type xy to be created", which is what you are asking for. However, as you will set it as the Views DataContext in the constructor and as the DataContext can change after creation of the View, you cannot be sure that the View won't get a new ViewModel assigned after creation. Even worse, you will not be able to use your control in XAML anymore, because it doesn't have a default constructor anymore.
According to your first question, it is not really clear why the ViewModel should exist prior to the View. If you need to read a resource value from your View and assign it to a property on your ViewModel, I would expect it to be the other way around? Or are you accessing the View in your ViewModel (don't!)?
The question is, why you have to ask this question in the first place. There is something pretty wrong in your (or your bosses...) concept: View and ViewModel are two entities which should really work without knowing about each other. The idea is to build applications that could work perfectly without a single View existing by just getting/setting values on ViewModels and to have Views which would compile any run perfectly well without ViewModels, just without anything to show or do... If you try to hack this approach, you're better off not using MVVM at all.
Related
I have an app that should display data based on variables from parameters received from calls of the ViewModel.
I have noticed two places in which the ViewModel gets called from, one is the intended call by the parent ViewModel for displaying the View of the child ViewModel with the help of ViewLocator.cs. Another is the DataContext required by the View to enable data binding.
Former: [ParentViewModel.cs]
public ParentViewModel()
{
UserControlContent = new ChildViewModel(genericParameter: "actual parameter");
}
Latter: [ChildView.axaml.cs]
public ChildView()
{
InitializeComponent();
DataContext = new ChildViewModel(genericParameter: "not the parameter I want");
}
So I want to pass in the "actual parameter" as shown above for show in the resulting View. I expect the final view to look like this:
But in reality I get this:
So, how can I work around this and get the View to display the right data?
Appreciate any input!
Turns out, only the call from the ParentViewModel is required. DataContext under ChildView can be removed and the correct parameter can be used.
Thanks to the answer here for this question.
I think you have some fundamental misunderstandings of MVVM.
Firstly, you have two ChildViewModel instances.
So calls made in your ParentViewModel on the UserControlContent instance of the view model will never be reflected in the UI as the ChildView creates a new instance of the ChildViewModel itself and then uses this instance for as it's DataContext.
You should make use of some form of IoC and DI your dependencies.
MVVM discourages the use of manual view model creation through the new keyword.
Unless there is a very specific use case, try to keep some relationship between the UI structure and your view models as flat as possible.
By this I mean if there is a use case where the parent view model needs the same things as the child view mode. It may make sense to flatten and merge those two view models.
This in turn simplifies the VMs themselves and the bindings.
I'm learning Silverlight/MVVM. Now I'm facing problem with Commands, that I think are just overcomplicated. I wanted to execute close on child window after command.
According to separation of concers it should be execute from view, as I understand.
As far as I looked for solution I found it and it wasn't trivial for such a trivial task.
To sum it up, I must say that separation of view, viewmodel and model are great ideas.
Also Binding from View to ViewModel is nice and clean.
But what about Commands. As I understand they are just piece of code to execute (like delegates).But they are too complicated and troublesome.
I want to know you opinion. What about idea that VieModel would have properties and normal public methods, that it will be executed from events of views. If I will not pass any view related element to the view model it still will be MVVM, right?
Of course, there will be one drawback, that i will have to bind separatly IsEnabled to properties in ViewModel to mimic CanUpdate functionality of Commands. It's not that you view doesn't know about ViewModel.
Views are not very testable, are they?
It would be very flexible. For example, in event for click i would do some strict view logic, call method from viewmodel object and then maybe call another method and after all that do some more view logic.
So, what do you think?
You can try using Cailburn.Micro. It is an open-source framework that runs over WPF and hides some of it complexities. For example, it replaces command-classes with just plain method calls.
You can implement windows-closing by returning a special result that will do the actual closing of the view. That way your ViewModel will still be fully unit-testable, as you can check that expected result is returned, and it will not be view-aware.
Here is an example on how to implement this: https://stackoverflow.com/a/10175228/258737
I'm currently in the need of setting the SelectedIndex property of my TabControl when a certain event (IEventAggregator) takes place and thought about how I'd implement that.
I came up with 2 possibilities:
Use GetView() provided by ViewAware in order to access my TabControl and set the SelectedIndex to my value
Use a property in my associated ViewModel and bind this property to my TabControl's SelectedIndex property via XAML
Both options are working fine but I personally want to get this question answered since this is not the first time I'm wondering where to implement the functionality in such cases.
I know that the first option won't enable the Notify support but besides that: What would be the proper way?
Having a GetView() method to manipulate the view directly from the viewmodel completely breaks MVVM. You might as well just put all your logic in codebehind. The whole point of MVVM is to abstract away the actual view so that it is decoupled from the logic, and the app can be unit tested.
What if you change your mind about the tabs in the future and decide to show your multiple views some other way? You've now got to start editing your viewmodel to edit the new view instead of just tweaking some XAML.
And for unit testing you're going to have no way to mock out your TabControl.
I'm creating a simple database application in C# WPF using MVVM as Relay Commands and databinding. For in-memory storage of database content I use ObservableCollection, which is binded to the Datagrid as follows:
<DataGrid ItemsSource="{Binding Path=Softwares, Mode=OneWay}" SelectedItem="{Binding Path=SoftwareSelection, Mode=TwoWay}">
when the item is selected user can chose to edit it. For editation a form is opened with a bunch of textboxes with the data of given entity. All the fields are validated using IDataErrorInfo, unless all textboxes are valid, the ok button is not enabled, and therefore no changes can be saved to the collection and to the database.
Here is how the example textbox looks like:
<TextBox Text="{Binding Name, Mode=TwoWay, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged, ValidatesOnExceptions=True}"/>
But the tricky part is, in case I change some values in textboxes and then close the window, the new values are propagated to the ObservableCollection, which I don't want to. Do you have any idea, how to prevent such behaviour? I would like the databinding work only after clicking the button. Otherwise the databindng works well, so as the button (dis/en)abling and reflecting changes to the database and to the collection after clicking. Both views are serviced by different ViewModels, data between views are passed by firing events.
I tried to add to the DataGrid UpdateSourceTrigger=Explicit to the ItemsSource binding, but didn't help. Perhaps, I'm missing some application logic?
Thank you very much for your help.
This is where most WPF developers make mistakes of assumptions!
In MVVM dirty data can be stored in the ViewModel and that's what the layer of VM is for! It mimics the View from Model's perspective and because View is in error, the ViewModel would also be in the error. Thats perfectly valid.
So having said that, the question remains
How will you NOT allow the temporary / dirty data to flow to your
ObservableCollection?
Two ways...
If your ObservableCollection is specific to your model class (say MyItem) then if your Model class (MyItem) is an Entity class \ DAL class \ NHibernate class create a wrapper of MyItem class called ViewModelMyItem and then instead of ObservableCollection<MyItem> use ObservableCollection<ViewModelMyItem>.
This way dirty data from your View would be inside ViewModelMyItem and it can only be legitimately flown back to your model class (MyItem) ONLY when Save button is clicked. So that means in Save Command's Execute() delegate you can copy \ clone the ViewModelMyItem's properties into Item's properties, if validations in ViewModelMyItem are fine.
So if Item is an EntityType class / NHibernate class / WCF client model class, it would always only valid data as ViewModelMyItem is filtering the temporary / dirty information upfront.
You could use Explicit binding model. It stops the TwoWay data to flow back to the sorce Item unless BindingExpressions.UpdateSource() is explicitly called.
But according to me, this defeats MVVM in straightforward way because ViewModel will not have what UI is showing! Still however you can use *Attached Behavior * to govern explicit binding by staying in MVVM space!
Let me know if this helps!
You're better off putting the code into the domain object's property setter. Then synchronize with the visuals by triggering the NotifyPropertyChanged handler.
More on this topic:
http://msdn.microsoft.com/en-us/library/ms743695.aspx
http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx
Setting the Binding Mode to Explicit should require you to call the binding expressions UpdateSource() method to send changes back to your model. Because you only mentioned that you set Explicit on the DataGrid's binding, I'm guessing you only need to make sure that you have that mode explicitly set on any property that is being bound directly back to your model. Such as your TextBox's Text Binding, in the case above. That will likely fix your problem but require you to call UpdateSource() on each target's BindingExpression one way or another.
If you're using one of the mainstream ORM's (EF, Linq to SQL, etc), then chances are your Entities automatically implement INotifyPropertyChanged and INotifyPropertyChanging. Because you are sharing a reference to your single instance, all changes in your edit will be reflected in your main view and anything else Binding to that instance. As a dirtier alternative, you can just create a separate instance of the same type and manually copy the values back over when the window's dialog result is true.
The first approach requires you to manually update the bindings, the second approach requires you to manually update the values from the Edit's instance.
With some more code, I can help with your specific approach.
i am writing an application that has a viewmodel and a usercontrol that displays
data from this viewmodel. The viewmodel contains an entity "Appointment", and those
appointments have a property "UserName".
When I display the appointments, I want to use a value-converter to get a color for
the user (depending on "UserName"), but the colors are not contained in the entity "Appointment", so I wanted to create a value-converter that uses the entity "User" from the viewmodel.
What is the best way to use another entity from the viewmodel inside the converter?
Is it possible to access the viewmodel from the usercontrol? I tried to place the converter inside my viewmodel-class, but can I access this class from the usercontrol?
I figured out that the following possibilities might work:
Adjust the viewmodel so that each appointment also contains the color. But I don't want to do this because I don't want to mess with the viewmodel.
Set the converter-parameter from the class that also contains the viewmodel at startup. (Does this work?)
Use x:Reference to databind the converter parameter to the viewmodel that is unknown at compile-time.(Is this possible?)
Converter parameter is the way to go.
Why is the viewmodel unknown at compile time?
Bindings are not compile time checked anyway.
Is the UserControl.DataContext being set to an instance of Appointment, you should be able to set the parameter to {Binding UserName} or {Binding Appointment.UserName} depending on exactly what you are setting as the DataContext on the UserControl.
I would suggest that you re-examine your reluctance to modify the view model. The purpose of having a view model in the first place is so that everything that the view needs can be found in one place. Coming up with elaborate value converters to prevent modifying the view model is an approach that gets increasingly unmaintainable the more you do it.