Building a data entry form in wpf - wpf

I'm trying to build a data entry form in wpf. To perform validation I apparently need to have an object attached in the datacontext of my grid. But how can I have one when I didn't create one yet?
How does it work?
For example, I have a screen with a datagrid. The datagrid contains users that were obtained from membership. Above the grid is a button: add user. When clicked a new window appears and the following can be entered: user name, password, email. To perform validation on the textboxes to see if they aren't empty. Now, it is my understanding that the way this works is by having an object attached to the window (datagrid datacontext). But how can I have it attached when it doesn't exist yet?

This is a case where MVVM design patterns are very useful.
Every WPF view has a corresponding view model object that the properties in the view are bound to. So your window with the data grid has a view model - its DataContext - and the view model has properties that are bound to properties in the view - e.g. the ItemsSource in the data grid is bound to a collection (see note 1).
The "add user" command (which is implemented as a RelayCommand in the window's view model) creates a new view (the new window) and its corresponding view model object (the new user), sets the view's DataContext to the view model, and calls ShowDialog to show the window. (See note 2.) If the user accepts the new object, ShowDialog returns true, and the logic in the command takes the view model object (which now contains whatever changes the user made) and uses the information in it to create a new model object and add it to the model. If the user cancels, ShowDialog returns false, and the command discards the view model object without creating a new model object.
Note 1: The collection here may be a collection of model objects, or it may be a collection of view model objects. It depends on whether or not you need anything that's not in the model for displaying the model objects in a data grid. It's common, in this kind of scenario, for the objects in the grid to be view models for the dialog - that is, the view model objects have properties implemented for both display in the grid and modification in the dialog window. On the other hand, if all the grid is doing is displaying data from the model, there may be no need for an intermediary object.
Note 2: Having the command create a WPF window violates a central MVVM design principle, which is that view models shouldn't create WPF objects. The reason for this principle is pretty simple: you can't build an automated unit test for this command, since it's just going to throw up a dialog and wait. There are all kinds of different approaches to this - see, for instance, this question, and Josh Smith's blog post on the Mediator pattern - and all of them involve delegating the creation and display of the actual dialog window to a separate service that can be mocked out for unit testing. If you don't want to choose one of those approaches up front, you can retrofit one into your application once you get this thing working.

The idea here is that you should attach an object which is slightly different from your business models. In your case it won't UserInfo (or whatever you have for users in grid). It will be some other class, more suitable for editing. In MVVM this class will be a ViewModel. This class will have some differences comparing to your regular user class, for example it may have some properties nullable (when you haven't set them yet). Also this class will handle validation. You should instantiate this class at the same time you're creating an editor window and put instance of this class into Window.DataContext.

Hmm, there is a lot in this question but I just created a screen with three data grids (I am using Telerik in this case) and under each datagrid is a button to add to the grid. No the window with the three datagrids has it's own view model. and each of the "pop up's" has it's own viewmodel, in this case all of these are user controls and I just create a new window and set window.content and call show dialog.
Communication is facilitated via "events" - not the standard events you are used to in .NET but in this case I am using Prism and it's CompositePresentationEvent class. When the user is done creating their new object they click add and I fire off this event with the "payload" being the object they created. The main window with the three grids listens for that event and has a method to handle it, in this case adds it to the ObservableCollection which is what I bind the grids to.
If I were you I would look into the various frameworks that are out there, Prism, MVVM light etc... Again, your question seemed rather broad, I tried to give an overview but I didn't go into detail, if you look into some sort of framework I think it will clear up a lot of these details for you.

When the users hit Add New, create a new blank copy of your object, and set the datacontext to that new object.
Set some kind of flag to identify that it is a New object. This can be the Id being NULL, 0, -1, etc or an ObjectState property set to New. That way all your validation rules apply, and once the user hits save you know to INSERT instead of UPDATE

Related

How to assign context and refresh it in Entity Framework?

I created a new entity object and bound it to controls in another window (edit window). After modifying and saving I assigned a new entity object into the one in the main window. The old entity object is bound into a datagrid, now I want the datagrid to display the data that I had modified and saved.
ObjectContext.Refresh Method (RefreshMode, Object) seems to be what I want but I don't know how to use it correctly.
In short :
I have a main window with datagrid displaying the whole data of the table. Users can pick one row and edit it in a edit window. After saving, the datagrid should display what has been modified.
Your best bet here is to use an ObservableCollection as your data source for the datagrid instead of the query.
And look at implementing INotifyPropertyChanged interface in your Customer class.
The ObservableCollection is initially populated by the database query. User changes are made to elements within the ObservableCollection and once complete you then just need to trigger transferring the changes to wherever you originally obtained your list of Customer objects
By doing this changes made both to the collection of Customers and to individual Customer objects (if present within the datagrid) will be automatically updated for you.
edit
I must admit that I'm a bit rushed to offer up any code at the moment, but here's a pretty good article that explains how to use ObservableCollections and classes that implement INotifyPropertyChanged. It also has code examples, which although in VB.NET should give you enough of an idea to get started.
In effect you separate your code into distinct layers UI (View), business logic (View Model) and data layer (Model where your entity framework resides).
You bnd your datagrid to the ObservableCollection type property in your Customers class and your edit csutomer window is bound to as instance of your Customer class.

Creating a tabcontrol in MVVM from a central datasource

I am new to MVVM, and I am trying to implement a simple application, following the pattern.
For simplicity, I am breaking the problem down to it's simplest form. If I manage to get this to work, I will have little trouble getting the application made.
The simple application consists of a tabcontrol. It is important that both tabs have their own ViewModel. However, they will get most of their data from the same source. The main issue is to get the second tab to know that the first have initiated a change on the datasource.
So, for simplicity, let's just say that the model is holding a single integer. This integer needs initially to be set to 1.
The first tab is holding a textblock and a button. The text of the textblock is bound to the integer in the datamodel. Upon pressing the button, the integer in the moddel should be incremented with 1.
The second tab holds only a textblock, also bound to the integer in the datamodel. The challenge is to get this textblock to update along with the first textblock, but still being it's own viewmodel.
I need somewhere central to store the values of the model, and in some way, let the viewmodels know that they have been updated, so their properties can be updated, and the Views therefore get's updated accordingly.
Can someone explain in as much detail as possible how this is done? I have tried a billion different ways, but I am not getting it to work.
Let me see if I have your question down right:
You have a data source (your model).
You have 2 view models.
View model 1 changes data in the model.
View model 2 needs to update with changes in the model.
If that all sounds right, here's one solution:
Have your model implement INotifyPropertyChanged. When the integer changes, raise the PropertyChanged event. In view model 2, listen for the model's PropertyChanged event. When it occurs, raise view model 2's property changed event, and its UI will get updated automatically.
I have no idea in which scenario you want to do that.
But a solution that crosses my mind is to have a "parent" ViewModel that holds instances of the two tab ViewModels.
e.g.
public class ParentViewModel{
private Tab1ViewModel viewModel1;
private Tab2ViewModel viewModel2;
}
Then the ParentViewModel can subscribe to the INotifyPropertyChanged event of the ViewModel1 and set the value on the ViewModel2.
I have recently implemented something similar to this. It was for implementing a wizard, consisting of:
7 Views
8 View models
1 Model
The main ViewModel created the Model and passed this on to all the other view models through their constructors.
In your scenario you could have a main ViewModel with an ObservableCollection of ViewModels. Each of these VM's would have the same instance of the model as their data source.
As previously mentioned, implement INotifyPropertyChanged on the model and bind the views directly to the model through a property on the ViewModel. I found this diagram very useful : http://karlshifflett.files.wordpress.com/2009/01/wpflobmvvm1.png

Should a ViewModel in MVVM reference the View?

In the MVVM (Model-View-ViewModel) pattern should the ViewModel reference the view. I would think that it should not. But how should the following scenario be handeled? I have a view that has a tab control as the main container, the viewmodel for this view implements a command to add a new tab to the tab control. The easy way would be to allow the viewmodel to reference the view and then in the command implementation to just programmatically add the new tab to the tabcontrol in the view. This just seems wrong. Should I somehow bind the tabcontrol to the viewmodel and then implement a data/control-template to add the new tabs. I hope this makes some kind of sense to somebody :)
In "pure" MVVM, the ViewModel shouldn't really reference the View. It's often convenient, however, to provide some form of interface in the View whereby the ViewModel can interact with it.
However, I've found that I almost never do that anymore. The alternative approach is to use some form of attached property or blend behavior within your View, and bind it to your ViewModel properties. This allows you to keep the View logic 100% within the View. In addition, by creating a behavior for this, you create a reusable type that can be used to handle this in every ViewModel->View interaction. I strongly prefer this approach over having any View logic within the ViewModel.
In order to demonstrate this technique, I wrote a sample for the Expression Code Gallery called WindowCloseBehavior. It demonstrates how you can use a Behavior within the View bound to properties in the ViewModel to handle controlling a Window's life-cycle, including preventing it from being closed, etc.
Reed and Dan covered the general approach but in reference to your specific case, TabControl is an ItemsControl and so can bind its ItemsSource to a data collection in your ViewModel representing the set of tabs to display. The UI for each type of tab can then be represented by a DataTemplate specific to the data type of an item (either using DataType or a DataTemplateSelector). You can then add or remove data items as needed from your VM and have the tabs update automatically without the VM knowing anything about the TabControl.
I find that it's often a helpful compromise to expose an interface on the View that handles View-specific functionality. This is a good way to handle things that are awkward to accomplish with pure binding, such as instructing the form to close, opening a file dialog (though this often gets put in its own service interface) or interacting with controls not designed well for data binding (such as the example you provided.)
Using an interface still keeps the View and ViewModel largely decoupled and enables you to mock the specific IView during testing.
One of us is missing something obvious. Your tab control is an ItemsControl. You should bind the ItemsSource of your tab control to an ovservable collection in your view model. When you handle the command in your view model to add a tab, you simply add a new element to this collection and, voila, you've added a new tab to the control.

WPF MVVM Drag and Drop onto another Control to raise an event only

I've got two ListBox's with objects as an ItemsSource populating them. Right now, I'm using a DragDropHelper to let me drag an object from one ListBox to the 2nd ListBox. I run custom code to change an attribute on the Object and update my two ListBox collections of objects.
However, now I want to be able to drop one of these objects onto another control in the window. But, I dont want to necessarily "DROP" the object. I just want the external control to realize (by raising an event) that it just got dropped onto by an object with an ID.
To recap, I've got 2 listboxes. one listbox is Favorites, the other is NonFavorites. I can happily drag/drop between the two listboxes and everything works. now i want to drag a favorite/nonfavorite away from the listboxes and drop it onto another control. I want that control to simply say "HEY! I just got a favorite/nonfavorite object dropped on me".
any ideas?
I did something similar to this last year (.NET .3.5).
If I remember correctly when you "Drop" an object which has been selected and dragged (via the adorner layer) you are in essence holding a reference to the selected object. When that object is "Dropped" the "InstanceDroppedOnUserControlFoo_Handler(... args)" event handler has a untyped reference to the object that has been dropped.
From this you can cast (if the type is known) and access the Id field to your hearts content.
The question now is, does the drop target user control share the same ViewModel in it's DataContext as that of the Drag Source? As in most cases where this is not the case you will not get a reference in the event args, you will get null.
If this is the case you will need to explore these options for inter ViewModel communication:
Use a MVVM message passing framework (MVVM Light Framework see Messenger component)
or
Pub Sub composite events via the WPF Prism - EventAggregator:
Then follow this process (or something more tailored to your needs):
When an item has been selected and is being Dragged, hold its reference in a property of your Drag Source's ViewModel.
When the item is dropped, publish a message saying "I want the reference to the selected item which was being dragged".
The Drag Source can publish a message in response with the reference to the object which was dragged which will be received by the requesting ViewModel.
Obviously you can tailor the reference holding at this point to your needs. I will leave you with one last suggestion, it may be worth while considering the use of a controller class which manages this kind of operation. I have seen a controller being used by the Microsoft's Patterns & Practises in coordination with MVVM in the WPF CAG (PRISM) samples, so it is not unheard of.

What is the best way for the ViewModel to manipulate the View?

I understand that in the MVVM pattern, that a ViewModel should know nothing about the View.
So there seems to be two ways that the ViewModel can cause something particular to happen on the UI, consider this common flow of events:
user types something in a textbox
user clicks button
button calls DelegateCommand called "Save" on viewmodel
view model saves text from textbox
if everything goes well during the save, the view model changes its INotifyPropertyChanged property called SaveStatus to "Succeeded"
Now in the View, I have two ways to allow this change to have an effect on the UI:
in the View there could be a Textblock that has a Converter on it that converts the text of SaveStatus to a phrase such as "The save succeeded."
in the View there could be a Trigger that checks to see if SaveStatus = "Succeeded" and if so, then a series of Setters change the UI appropriately (hiding elements, changing texts, changing colors, etc.)
Is this the basic flow of information from ModelView to View that you use in your applications?
You can also create custom events on the viewmodel and have the view subscribe to them and react accordingly. You shouldn't need to do this very often, but it makes more sense than inspecting every INotifyPropertyChanged event for particular property names.
Is this the basic flow of information from ModelView to View that you use in your applications?
Yes. We use INotifyPropertyChanged almost exclusively for changes from the ViewModel to the view. Where the interaction is a bit more complex we use other events that the View hooks up to.
Instead of a SaveStatus message property we have a HasChanges boolean on an EditableAdapter, which wraps our POCO and provides commit/rollback of changes, as well as other calculated properties. Then we can bind our Views to this HasChanges so that, for example, we can display the documents name with a * on the end to show it has changes, or use the HasChanges to disable/enable a Save button.
We are using the model view controller pattern, so it goes like this:
user types something in a textbox
user clicks save button
the view tells the controller to save the data
the controller tells the view to fetch the data
the controller saves the data to the model
the controller signalizes the view that the save succeeded
the view shows "The save has succeeded"
I think you could use pretty much the same approach (the only difference would be that controller and model would be both the view model in your example)

Resources