I am new to WPF. I am currently developing an application in WPF where I had to enable/disable a button based on a value from database. I found solutions on the net to do so using Command as well as Converters. So which one is a better solution and why?
When working with buttons it would be best to use the command implementation , since it is built in
and you can provide a command parameter for predicate , the converter is something you would need to
write , instance and place in each place you would wan't to use it .
To summarize a command with CanExecute would be more reusable and maintainable .
Since you're new to WPF, I truly recommend you start learning Rx Extensions and Reactive UI as well.
Reactive UI provides a Command Framework that can really help you in complex scenarios where your commands depend on many flags/conditions that can be computed through lambda functions and Observables.
If you want to create a complex Application you should definitely start learning MVVM. For a simple application use MVVM Light. For more complex WPF applications you can go for Reactive UI or Microsoft PRISM.
Have a look at Reactive UI here . There's a few Command examples in the Home page of Reactive UI but you can also get more samples in here
For instance you could declare an ICommand like this:
DisplayCommand = new ReactiveCommand(this.WhenAny(x => x.Name, x => !string.IsNullOrEmpty(x.Value)));
Have a look at the documentation.
As mentioned previously, you should use a Command instead of a converter for this scenario.
In addition, if the events you want to listen for are other ones besides click then use the System.Interactive behaviors/actions as described here.
Related
I'm learning ReactiveUi and trying the sample from here https://reactiveui.net/docs/getting-started/ This is a great examle, but now I would like to replace the List SearchResults with a ICollectionView to have more grouping / sorting capability.
The documentation contains a ReactiveCollectionViewSource here and but I'm unable to find a sample how to use it with the starting code. Is that the right track?
The ReactiveCollectionViewSource is for the iOS project only.
You should be able to use standard WPF ways of generating your CollectionView and use CollectionViewSource.GetDefault() etc.
You can then use WPF or ReactiveUI bindings to bind that to your controls.
One thing of note is that DynamicData is going to be in the near future the preferred solution for data management in RxUI projects. Worth seeing if it fits in your problem space. https://github.com/RolandPheasant/DynamicData - There is a DynamicData channel on the Reactive slack channel if you need help with the framework https://reactiveui.net/slack
I'm new to catel and mvvm. I 've successfully built a sample application the "catel" way and I like all the added features which I do need (thank you for the great tutorials). I've successfully run a sample app using typical mvvm and a 3rd party control printing reports. When I tried to use the 3rd party control in the catel application I had issues making it work, even with the information provided in catels' documentation. Even if I do manage it to work, I don't want to make custom base classes to add new controls, because most of my controls are special (3D). So, my question: can I use all of the catel features, including model and viewmodel capabilities, but use external windows and controls with the typical manual binding procedure? Do I need to know of any special concerns?
I learn catel since 2 weeks too, welcome into the Catel World :)
So, you can create custom window base class with IDataWindow and your window inherit Catel features. Need more coding but not a lot !
I suggest you to consult the excellent documentation here for Custom Window and here for Custom Control
Hope it's help !
Dams
I am currently working with the Microsoft MVVM template and find the lack of detailed examples frustrating. The included ContactBook example shows very little Command handling and the only other example I've found is from an MSDN Magazine article where the concepts are similar but uses a slightly different approach and still lack in any complexity. Are there any decent MVVM examples that at least show basic CRUD operations and dialog/content switching?
Everyone's suggestions were really useful and I will start compiling a list of good resources
Frameworks/Templates
WPF Model-View-ViewModel Toolkit
MVVM Light Toolkit
Prism
Caliburn
Cinch
Useful Articles
WPF Apps With The Model-View-ViewModel Design Pattern
Data Validation in .NET 3.5
Using a ViewModel to Provide Meaningful Validation Error Messages
Action based ViewModel and Model validation
Dialogs
Command Bindings in MVVM
More than just MVC for WPF
MVVM + Mediator Example
Application
Screencasts
Jason Dolinger on Model-View-ViewModel
Additional Libraries
WPF Disciples' improved Mediator Pattern implementation(I highly recommend this for applications that have more complex navigation)
MVVM Light Toolkit Messenger
Unfortunately there is no one great MVVM example app that does everything, and there are a lot of different approaches to doing things. First, you might want to get familiar with one of the app frameworks out there (Prism is a decent choice), because they provide you with convenient tools like dependency injection, commanding, event aggregation, etc to easily try out different patterns that suit you.
The prism release:
http://www.codeplex.com/CompositeWPF
It includes a pretty decent example app (the stock trader) along with a lot of smaller examples and how to's. At the very least it's a good demonstration of several common sub-patterns people use to make MVVM actually work. They have examples for both CRUD and dialogs, I believe.
Prism isn't necessarily for every project, but it's a good thing to get familiar with.
CRUD:
This part is pretty easy, WPF two way bindings make it really easy to edit most data. The real trick is to provide a model that makes it easy to set up the UI. At the very least you want to make sure that your ViewModel (or business object) implements INotifyPropertyChanged to support binding and you can bind properties straight to UI controls, but you may also want to implement IDataErrorInfo for validation. Typically, if you use some sort of an ORM solution setting up CRUD is a snap.
This article demonstrates simple crud operations:
http://dotnetslackers.com/articles/wpf/WPFDataBindingWithLINQ.aspx
It is built on LinqToSql, but that is irrelevant to the example - all that is important is that your business objects implement INotifyPropertyChanged (which classes generated by LinqToSql do). MVVM is not the point of that example, but I don't think it matters in this case.
This article demonstrates data validation
http://blogs.msdn.com/wpfsdk/archive/2007/10/02/data-validation-in-3-5.aspx
Again, most ORM solutions generate classes that already implement IDataErrorInfo and typically provide a mechanism to make it easy to add custom validation rules.
Most of the time you can take an object(model) created by some ORM and wrap it in a ViewModel that holds it and commands for save/delete - and you're ready to bind UI straight to the model's properties.
The view would look like something like this (ViewModel has a property Item that holds the model, like a class created in the ORM):
<StackPanel>
<StackPanel DataContext=Item>
<TextBox Text="{Binding FirstName, Mode=TwoWay, ValidatesOnDataErrors=True}" />
<TextBox Text="{Binding LastName, Mode=TwoWay, ValidatesOnDataErrors=True}" />
</StackPanel>
<Button Command="{Binding SaveCommand}" />
<Button Command="{Binding CancelCommand}" />
</StackPanel>
Dialogs:
Dialogs and MVVM are a bit tricky. I prefer to use a flavor of the Mediator approach with dialogs, you can read a little more about it in this StackOverflow question:
WPF MVVM dialog example
My usual approach, which is not quite classic MVVM, can be summarized as follows:
A base class for a dialog ViewModel that exposes commands for commit and cancel actions, an event to lets the view know that a dialog is ready to be closed, and whatever else you will need in all of your dialogs.
A generic view for your dialog - this can be a window, or a custom "modal" overlay type control. At its heart it is a content presenter that we dump the viewmodel into, and it handles the wiring for closing the window - for example on data context change you can check if the new ViewModel is inherited from your base class, and if it is, subscribe to the relevant close event (the handler will assign the dialog result). If you provide alternative universal close functionality (the X button, for instance), you should make sure to run the relevant close command on the ViewModel as well.
Somewhere you need to provide data templates for your ViewModels, they can be very simple especially since you probably have a view for each dialog encapsulated in a separate control. The default data template for a ViewModel would then look something like this:
<DataTemplate DataType="{x:Type vmodels:AddressEditViewModel}">
<views:AddressEditView DataContext="{Binding}" />
</DataTemplate>
The dialog view needs to have access to these, because otherwise it won't know how to show the ViewModel, aside from the shared dialog UI its contents are basically this:
<ContentControl Content="{Binding}" />
The implicit data template will map the view to the model, but who launches it?
This is the not-so-mvvm part. One way to do it is to use a global event. What I think is a better thing to do is to use an event aggregator type setup, provided through dependency injection - this way the event is global to a container, not the whole app. Prism uses the unity framework for container semantics and dependency injection, and overall I like Unity quite a bit.
Usually, it makes sense for the root window to subscribe to this event - it can open the dialog and set its data context to the ViewModel that gets passed in with a raised event.
Setting this up in this way lets ViewModels ask the application to open a dialog and respond to user actions there without knowing anything about the UI so for the most part the MVVM-ness remains complete.
There are times, however, where the UI has to raise the dialogs, which can make things a bit trickier. Consider for example, if the dialog position depends on the location of the button that opens it. In this case you need to have some UI specific info when you request a dialog open. I generally create a separate class that holds a ViewModel and some relevant UI info. Unfortunately some coupling seems unavoidable there.
Pseudo code of a button handler that raises a dialog which needs element position data:
ButtonClickHandler(sender, args){
var vm = DataContext as ISomeDialogProvider; // check for null
var ui_vm = new ViewModelContainer();
// assign margin, width, or anything else that your custom dialog might require
...
ui_vm.ViewModel = vm.SomeDialogViewModel; // or .GetSomeDialogViewModel()
// raise the dialog show event
}
The dialog view will bind to position data, and pass the contained ViewModel to the inner ContentControl. The ViewModel itself still doesn't know anything about the UI.
In general I don't make use of the DialogResult return property of the ShowDialog() method or expect the thread to block until the dialog is closed. A non-standard modal dialog doesn't always work like that, and in a composite environment you often don't really want an event handler to block like that anyhow. I prefer to let the ViewModels deal with this - the creator of a ViewModel can subscribe to its relevant events, set commit/cancel methods, etc, so there is no need to rely on this UI mechanism.
So instead of this flow:
// in code behind
var result = somedialog.ShowDialog();
if (result == ...
I use:
// in view model
var vm = new SomeDialogViewModel(); // child view model
vm.CommitAction = delegate { this.DoSomething(vm); } // what happens on commit
vm.CancelAction = delegate { this.DoNothing(vm); } // what happens on cancel/close (optional)
// raise dialog request event on the container
I prefer it this way because most of my dialogs are non-blocking pseudo-modal controls and doing it this way seems more straightforward than working around it. Easy to unit test as well.
Jason Dolinger made a good screencast of MVVM. Like Egor mentioned there is no one good example. They are all over. Most are good MVVM examples, but not when you get into complex issues. Everyone has their own way. Laurent Bugnion has a good way to communicate between viewmodels as well. http://blog.galasoft.ch/archive/2009/09/27/mvvm-light-toolkit-messenger-v2-beta.aspx Cinch is also a good example. Paul Stovel has a good post that explains a lot too with his Magellan framework.
Have you looked at Caliburn? The ContactManager sample has a lot of good stuff in it. The generic WPF samples also provide a good overview of commands. The documentation is fairly good and the forums are active. Recommended!
Found this one useful. Has code too.
http://msdn.microsoft.com/en-us/magazine/dd419663.aspx
I have written a simple MVVM example from scratch on code project here is the link MVVM WPF step by step.
It starts from a simple 3 layer architecture and graduates you to use some framework like PRISM.
The sample project in the Cinch framework shows basic CRUD and navigation tools. It's a fairly good example of using MVVM, and includes a multi-part article explaining its usage and motivations.
I also shared in your frustration. I'm writing an application and I had these 3 requirements:
Extensible
WPF with MVVM
GPL compatible examples
All I found were bits and pieces, so I just started writing it the best I could. After I got into it a bit, I realized there might be other people (like yourself) who could use a reference application, so I refactored the generic stuff out into a WPF/MVVM application framework and released it under the LGPL. I named it SoapBox Core. If you go to the downloads page, you'll see it comes with a small demo application, and the source code for that demo application is also available for download. Hope you find that helpful. Also, email me at scott {at} soapboxautomation.com if you want more info.
EDIT: Also posted a CodeProject article explaining how it works.
Here I am adding link of a WPF(Inventory Management App) application which using MVVM architecture designed by me .
Its UI is awesome.
https://github.com/shivam01990/InventoryManagement
Even I shared the frustration until I took the matter into my hands. I started IncEditor.
IncEditor (http://inceditor.codeplex.com) is an editor that tries to introduce developers to WPF, MVVM & MEF. I started it and managed to get some functionality like 'theme' support. I am no expert in WPF or MVVM or MEF so I can't put a lot of functionality in it. I make a sincere request to you guys to make it better so that nutters like me can understand it better.
I'm currently working on a brownfield application, it's written with winforms,
as a preparation to use WPF in a later version, out team plans to at least use the
MVVM/Presentation model, and bind it against winforms...
I've explored the subject, including the posts in this site (which i love very much),
when boiled down, the main advantage of wpf are :
binding controls to properties in xaml.
binding commands to command objects in the viewmodel.
the first feature is easy to implement (in code), or with a generic control binder, which binds all the controls in the form.
the second feature is a little harder to implement, but if you inherit from all your controls and add a command property (which is triggered by an internal event such as click), which is binded to a command instance in the ViewModel.
The challenges I'm currently aware of are :
implementing a commandmanager, (which will trigger the CanInvoke method of the commands as necessery.
winforms only supports one level of databinding : datasource, datamember, wpf is much more flexible.
am i missing any other major features that winforms lacks in comparison with wpf, when attempting to implement this design pattern?
i sure many of you will recommend some sort of MVP pattern, but MVVM/Presentation model is the way to go for me, because I'll want future WPF support.
Thanks in advance,
Erik.
Please take a look at Update Controls .NET. It is an open-source library for Winforms, WPF, and Silverlight that keeps controls up to date as data changes. You can start using it now for Winforms, and then transition over to WPF without changing your Data Model or View Model code.
Unfortunately, it does not solve the Winforms command binding problem. Your button click events will not port from Winforms to WPF. But it does take care of the data binding problem.
You might find the WAF Windows Forms Adapter interesting. It shows how to apply the Model-View-ViewModel (MVVM) Pattern in a Windows Forms application. The Adapter implementation provides a solution for the missing Command support in Windows Forms.
I don't develop too many desktop / Windows Forms applications, but it had occurred to me that there may be some benefit to using the MVC (Model View Controller) pattern for Windows Forms .NET development.
Has anyone implemented MVC in Windows Forms? If so, do you have any tips on the design?
What I've done in the past is use something similar, Model-View-Presenter.
[NOTE: This article used to be available on the web. To see it now, you'll need to download the CHM, and then view the file properties and click Unblock. Then you can open the CHM and find the article. Thanks a million, Microsoft! sigh]
The form is the view, and I have an IView interface for it. All the processing happens in the presenter, which is just a class. The form creates a new presenter, and passes itself as the presenter's IView. This way for testing you can pass in a fake IView instead, and then send commands to it from the presenter and detect the results.
If I were to use a full-fledged Model-View-Controller, I guess I'd do it this way:
The form is the view. It sends commands to the model, raises events which the controller can subscribe to, and subscribes to events from the model.
The controller is a class that subscribes to the view's events and sends commands to the view and to the model.
The model raises events that the view subscribes to.
This would fit with the classic MVC diagram. The biggest disadvantage is that with events, it can be hard to tell who's subscribing to what. The MVP pattern uses methods instead of events (at least the way I've implemented it). When the form/view raises an event (e.g. someButton.Click), the form simply calls a method on the presenter to run the logic for it. The view and model don't have any direct connection at all; they both have to go through the presenter.
Well, actually Windows Forms implements a "free-style" version of MVC, much like some movies implement some crappy "free-style" interpretation of some classic books (Romeo & Juliet come to mind).
I'm not saying Windows Forms' implementation is bad, it's just... different.
If you use Windows Forms and proper OOP techniques, and maybe an ORM like EntitySpaces for your database access, then you could say that:
The ORM/OOP infrastructure is the Model
The Forms are the Views
The event handlers are the Controller
Although having both View and Controller represented by the same object make separating code from representation way more difficult (there's no easy way to plug-in a "GTK+ view" in a class derived from Microsoft.Windows.Forms.Form).
What you can do, if you are careful enough. Is keep your form code completely separate from your controller/model code by only writing GUI related stuff in the event handlers, and all other business logic in a separate class. In that case, if you ever wanted to use GTK+ to write another View layer, you would only need to rewrite the GUI code.
Windows Forms isn't designed from the ground up to use MVC. You have two options.
First, you can roll your own implementation of MVC.
Second, you can use an MVC framework designed for Windows Forms.
The first is simple to start doing, but the further in you get, the more complex it is. I'd suggest looking for a good, preexisting and well-tested, MVC framework designed to work with Windows Forms. I believe this blog post is a decent starting point.
For anybody starting out, I'd suggest skipping Windows Forms and developing against WPF, if you have the option. It's a much better framework for creating the UI. There are many MVC frameworks being developed for WPF, including this one and that one.
According to Microsoft, the UIP Application Block mentioned by #jasonbunting is "archived." Instead, look at the Smart Client Application Block or the even newer Smart Client Software Factory, which supports both WinForms and WPF SmartParts.
Check into the User Interface Process (UIP) Application Block. I don't know much about it but looked at it a few years ago. There may be newer versions, check around.
"The UIP Application Block is based on the model-view-controller (MVC) pattern."
Take a look at the MS Patterns and Practices Smart Client application block which has some guidance and classes which walk you through implementing a model view presenter patter in windows forms - take a look at the reference application included.
For WPF this is being superseced by the prism project
The software factories approach is a great way to learn best practices