MVVM Implementation for WinForm application - c#

I am trying to implement MVVM (Model View ViewModel) pattern for my WinForms application. I am using C# 2005.
My application has a MainForm (View) with 2 multi line textboxes and 3 buttons. The purpose of the 1st textbox is to show a running commentary of what the application is doing, when the button is clicked. I keep on appending lines to the TextBox to update the user what is happening. The purpose of the 2nd textbox is to update the user about any error condition, conflicts, duplicate values; in short, anything which is required by the user to review. It classifies each message as either an INFO or a WARNING or an ERROR. Each of the 3 buttons perform an action, and keeps updating the 2 textboxes.
I have created a MainFormViewModel class.
1st question:
When the user clicks on the button in MainForm, I have to clear the contents of the 2 textboxes, and disable the button so that it cant be clicked again until 1st operation is completed. Should I do this textbox and button updation directly in the MainForm or I should use MainFormViewModel in some way?
2nd question:
The button click calls a method on the MainFormViewModel class. Before calling the method and after calling the method, I want to show a message in the 1st textbox something like "Operation A started / ended". I do this by calling a Common class which has a Log method to log messages to a TextBox or a file or both. Again whether it is ok to do this directly from the MainForm? I call this logging method at the start and end of the event handler.
3rd question:
How do I propagate error messages from ViewModel back to View? I have created a custom Exception class "TbtException". So do I have to write 2 catch blocks in each and every button, one for TbtException and other for genetic Exception class?
Thanks.

You should perform operations in the view only with regard to the state of the ViewModel object. E.g. you shouldn't assume the view model is calculating when you click a button, but you should add a state to the view model that says it's doing something longer and then recognize that state in the view. You shouldn't disable or enable buttons in the view as you please, but only if there's a state that demands these buttons to be changed. This can go as far as to have a property that indicates which item in a list is currently selected, so the UI doesn't call the list control's SelectedItem member, but the viewmodel's. And when the user clicks remove, then the view model will remove the selected member from its list and the view is automatically updated through state changes in the form of events.
Here's what I would call a view model for your view. It exposes messages through an observable collection to which the view can bind (ie. register event handlers, since binding is not well supported in WinForms). The textbox at any time renders only the contents of the collection. It has actions for clearing those collections which your view can call. The view can also call actions of the underlying model, but it should be updated through the viewmodel only! The view should never register any event handlers for events exposed by the underlying model. If you ever want to do that you should hook up that event in the view model and expose it to the view there. Sometimes that may feel like "just another level of indirection" which is why it may be overkill for very simple applications such as yours.
public class MainFormViewModel : INotifyPropertyChanged {
private object syncObject = new object();
private MainFormModel model;
public virtual MainFormModel Model {
get { return model; }
set {
bool changed = (model != value);
if (changed && model != null) DeregisterModelEvents();
model = value;
if (changed) {
OnPropertyChanged("Model");
if (model != null) RegisterModelEvents();
}
}
}
private bool isCalculating;
public bool IsCalculating {
get { return isCalculating; }
protected set {
bool changed = (isCalculating != value);
isCalculating = value;
if (changed) OnPropertyChanged("IsCalculating");
}
}
public ObservableCollection<string> Messages { get; private set; }
public ObservableCollection<Exception> Exceptions { get; private set; }
protected MainFormViewModel() {
this.Messages = new ObservableCollection<string>();
this.Exceptions = new ObservableCollection<string>();
}
public MainFormViewModel(MainFormModel model)
: this() {
Model = model;
}
protected virtual void RegisterModelEvents() {
Model.NewMessage += new EventHandler<SomeEventArg>(Model_NewMessage);
Model.ExceptionThrown += new EventHandler<OtherEventArg>(Model_ExceptionThrown);
}
protected virtual void DeregisterModelEvents() {
Model.NewMessage -= new EventHandler<SomeEventArg>(Model_NewMessage);
Model.ExceptionThrown -= new EventHandler<OtherEventArg>(Model_ExceptionThrown);
}
protected virtual void Model_NewMessage(object sender, SomeEventArg e) {
Messages.Add(e.Message);
}
protected virtual void Model_ExceptionThrown(object sender, OtherEventArg e) {
Exceptions.Add(e.Exception);
}
public virtual void ClearMessages() {
lock (syncObject) {
IsCalculating = true;
try {
Messages.Clear();
} finally { IsCalculating = false; }
}
}
public virtual void ClearExceptions() {
lock (syncObject) {
IsCalculating = true;
try {
Exceptions.Clear();
} finally { IsCalculating = false; }
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropetyChanged(string property) {
var handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(property));
}
}
EDIT: Regarding exception handling
I would rather catch exceptions in the ViewModel than in the view. The view model is better suited to prepare them for display. I don't know how that works in WPF though. I've yet to program an application in WPF, we're doing a lot of WinForms still.
Opinions may vary, but I think generic try/catch clauses aren't really exception handling. I think you should rather test your UI very well and include exception handling only when necessary. Which is why you unit test your view model and user test the view. However if you really stick to the principle and avoid logic in the view, you can do a lot with unit tests.

Related

How to handle events with MVC Pattern in C#

I'm implementing a mini program in C# using the MVC Architectural Pattern. The goal of this program is to update the value of a mouse click counter (which is in the Model), by clicking a button (which is in the View) through a Controller that must handle the Button Click Event.
The code I've written so far works (it compiles without errors), but if fails to handle the button click event because I can't figure out what kind of code I must put into the View and what into the Controller. The only solution I tried and found working is to give the View a reference to its Controller. In this way, the Event Handler is registered and implemented in the View and it invokes a method of the Controller (e.g. Controller.DoSomethingOnButtonClick()). But this solution breaks the MVC Pattern, because the View, as far as I understood, should NOT be aware of its Controller.
The Model (implements the Observer Pattern, it is the "observable"):
class Model : Subject
{
private int counter = 0;
public void IncreaseCounterByOne()
{
counter++;
Notify(); // notify the observers
}
public int GetCounter()
{
return counter;
}
}
The View (implements the Observer Pattern, it is the "observer"):
class View : IObserver
{
private Model Model;
private Form MyForm = new Form();
private Label MyLabel = new Label();
private Button MyButton = new Button();
public View(Model model)
{
this.Model = model;
this.Model.Attach(this);
}
public void CreateView()
{
// create and display the view (MyForm, MyLabel, MyButton)
}
public void Update(Subject subject)
{
UpdateLabel();
}
private void UpdateLabel()
{
MyLabel.Text = "Click Counter: " + Model.GetCounter();
}
}
The Controller:
class Controller
{
private Model Model;
private View View;
public Controller(Model model, View view)
{
this.Model = model;
this.View = view;
this.View.CreateView();
}
private void UpdateCounter()
{
this.Model.IncreaseCounterByOne();
}
}
What I want to achieve is that the Controller catch the Button Click Event generated by MyButton and handle it in its Event Handler, which I assume to be something like:
public void OnButtonClicked(object sender, EventArgs e)
{
UpdateCounter();
}
How can I accomplish this without using a reference to the Controller? Is it possible?
PS. I already read a lot of similar questions, but not found the solution I'm looking for.
You're running into a problem where trivial examples for patterns like MVC fall down: the UI often takes on both roles of V and C - it shows the data and offers a way to manipulate it. If your example were more involved (eg a web service is the controller)the concerns would be easier to see separated
The separation is still there logically, but you can't easily put the button in one class and the label that shows the counter in another as a method of separation, when you're essentially trying to combine it al in the same UI - but you shouldn't worry about this
Accept that your UI contains your view and also contains your controller so it's the UI class(es) job to unify all the things. Consider that your label is actually the view, not your class that happens to be called View. The concept appreciation you need to acquire is that you can have 3 different ways of changing the model (a timer, a button, a tcp socket that you send some data to) via the controller and 3 different ways of visualizing it (a label showing a number, a progress bar, a call to a website page that returns a string of 'A' as long as the current counter) and you've separated your concerns - the label/progbar/website are independent of the timer/button/website and they have no knowledge of each other, they don't interact, you don't need a reference to one passing into the other in order for everything to function. You can remove the button and the socket and the timer will carry on causing model manipulations that the label/progbar will carry on showing

Xamarin android with mvvm light : Textview binding only updates when a relaycommand is called

I setup a very simple app to get me started and trying things out. It has a label and two buttons. The buttons are linked to relaycommands in the main view model are used to send a message to a server using Mqtt which work as intended. The label is used to show part of the data received from the server. Everything seems to work fine except the labels won't update as soon as the message is received event though I can see in debugging that the property is set. The label will update as soon as I press one of the two buttons...
I'm new to the whole Xamarin android thing and have used mvvm light once in a WPF application.
Main Activity :
public partial class MainActivity
{
// UI Elements
public TextView ScanInfoLabel { get; private set; }
public Button UnlockButton { get; private set; }
public Button RegisterButton { get; private set; }
// Keep track of bindings to avoid premature garbage collection
private readonly List<Binding> _bindings = new List<Binding>();
// Get view model
private MainViewModel mainViewModel { get { return App.Locator.Main;}}
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set view from the "main" layout resource
SetContentView(Resource.Layout.Main);
// Get the UI elements by ID
ScanInfoLabel = FindViewById<TextView>(Resource.Id.ScanInfoLabel);
UnlockButton = FindViewById<Button>(Resource.Id.UnlockButton);
RegisterButton = FindViewById<Button>(Resource.Id.RegisterButton);
// Set Bindings for textviews
_bindings.Add(
this.SetBinding(
() => mainViewModel.ScanInfoLabel,
() => ScanInfoLabel.Text));
// Set the bindings for commands
UnlockButton.SetCommand("Click", mainViewModel.UnlockCommand);
RegisterButton.SetCommand("Click", mainViewModel.RegisterTagCommand);
}
In Main view model :
// RelayCommands
public RelayCommand UnlockCommand;
public RelayCommand RegisterTagCommand;
public RelayCommand MqttConnectCommand;
// Bindable properties
private string _scanInfoLabel = "Test";
public string ScanInfoLabel
{
get { return _scanInfoLabel; }
set { Set(ref _scanInfoLabel, value); }
}
// New scan message received
private void RFIDScanReceived(RFID.Scan scan)
{
ScanInfoLabel = BitConverter.ToString(scan.UID);
}
I would expect the label to show the data as soon as the mqtt message is received (which is then sent to the mainviewmodel using Messenger.Default.send<>() from mvvm light). But nothing is changed in the UI until I click on one of the buttons and then the correct information in displayed.
I don't really know where to start being new to xamarin android and none of my searches seemed to be of any help.
Any help will be appreciated, thanks!
ViewModels generally implement the INotifyPropertyChanged interface,
which means that the class fires a PropertyChanged event whenever one
of its properties changes. The data binding mechanism in Xamarin.Forms
attaches a handler to this PropertyChanged event so it can be notified
when a property changes and keep the target updated with the new
value.
Solution:
Make you model inherit from INotifyPropertyChanged and add PropertyChanged inside the set part. Then the labels will update as soon as the value of ScanInfoLabel changed.
public class BaseViewModel : INotifyPropertyChanged
{
// Bindable properties
private string _scanInfoLabel = "Test";
public string ScanInfoLabel
{
get { return _scanInfoLabel; }
set
{
_scanInfoLabel = ScanInfoLabel;
PropertyChanged(this, new PropertyChangedEventArgs("ScanInfoLabel"));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
You can refer:data-bindings-to-mvvm
Well I found out it was a threading issue since I set the property from a Messenger call. This apparently is not an issue in WPF which is why I was a bit stuck but using the DispatcherHelper did the trick.
// New scan message received
private void RFIDScanReceived(RFID.Scan scan)
{
DispatcherHelper.CheckBeginInvokeOnUI(() =>
{
ScanInfoLabel = BitConverter.ToString(scan.UID);
});
}

Passing data between view models in MVVM C#

I'm currently trying to create a "log" text box that gets messages between multiple view models (tied to multiple views) that I have. I've tried the approach described by user Blachshma here (Multiple Data Contexts in View) but it does not seem to be working.
I have three classes. Class AViewModel, Class BViewModel and Class ABViewModel.
The view for A binds to AViewModel using the following code in its constructor:
this.InitializeComponent();
this.model = new AViewModel();
this.DataContext = this.model;
The view for B and AB follows the same pattern.
The class structures are as follows:
public class A : INotifyPropertyChanged
{
private string log = string.empty;
public class A()
{
}
public string ALog
{
get
{
return this.log;
}
set
{
this.log = value;
this.NotifyPropertyChanged("ALog");
}
}
private void NotifyPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
/* Function that executes when relay command is clicked */
private void ExecuteCommand()
{
this.ALog += "here";
}
}
Class B is defined the same way with property BLog
Class ABViewModel has properties for each other view model
public class ABViewModel
{
public AViewModel AVM
{
get;
set;
}
public BViewModel BVM
{
get;
set;
}
}
In the xaml I simply have
<TextBox Text="{Binding ABViewModel.AVM}" />
My plan is to eventually using Multibinding to concatenate both logs together, but at the moment I can't even get the one View Model to update my string. It looks like my container view model ABViewModel isn't getting updated, but I don't really understand why, but I'm not entirely sure how to fix this.
Any suggestions are extremely appreciated!
Thanks!
Edit:
I debug my code and see that my string ALog is getting updated, but I don't see the change on the UI. For more information, I click a button that's connected to a RelayCommand in class A. This button invokes a method to connect to a COM port. I'm able to use the COM port from other view models successfully after opening it. The log is supposed to update saying that the com port was opened but I never see any text added to the log in the GUI even though the instance of ALog that I can debug through has the added text.
I can't use Prism or MVVM-light for this particular project.

Passing object to viewmodel

Question on the MVVM pattern where I think I have it wrong.
When a touchdown event occurs in a view I want to popup a message i.e.:
private void marker_TouchDown(MessageObject msgData)
{
CustomMessageControl message = new CustomMessageControl() {Width = 610, Height = 332};
CustomMessageViewModel messageVM = new CustomMessageViewModel(msgData);
message.DataContext = messageVM;
//Add to canvas
}
My viewmodel:
public class CustomMessageViewModel
{
public MessageObject message { get; set; }
public CustomMessageViewModel(MessageObject message)
{
this.MessageObject = message;
}
}
This works but doesn't feel right. Is this an acceptable way to populate the view model?
I believe that you are violating MVVM in creating the control in the view model. This isn't testable, your view model has to create the control now and that shouldn't be a requirement for testing (this emphasizes the lack of the separation of concerns between the UI and the view model).
Instead of creating the control, it is completely acceptable for your view model to fire an event of it's own. In this event, you'd pass the view model that you want the dialog/overlay/control to bind to, something like this:
public class CustomMessageControlEventArgs : EventArgs
{
public CustomMessageViewModel CustomMessageViewModel { get; set; }
}
public event EventHandler<CustomMessageControlEventArgs>
ShowCustomMessageControl;
private void marker_TouchDown(MessageObject msgData)
{
// Create the view model.
var message = ...;
// Get the events.
var events = ShowCustomMessageControl;
// Fire.
if (events != null) events(this,
new CustomMessageControlEventArgs {
MessageObject = new CustomMessageViewModel(msgData)
});
}
Then, in your UI code, you would bind to the event and then show the appropriate user interface for that event.
Remember, MVVM isn't strictly about being able to declare everything in XAML or binding data to the UI through just data bindings, it's about proper separation of code.
You want to separate the what of what is displayed (the view model) from the how of what is displayed (the UI); in firing an event, you're maintaining that separation of concerns.
Yes, you'll have to write some code behind (or you could do it through property notification changes, but it's uglier, frankly), but it maintains the separation and allows for easy testability without having to bring in any user interface elements.

How do I let the View know its have to close the Window?

I am using MVVM, from one I know the commnication for Data is View <=> ViewModel <=> Model.
The ViewModel can interact with View by using Two-Way binding.
But now I have a LoginView (which is in a Window), if the login successful will be check in ViewModel.
When it fail, it should tell the Window to close. But...how? The ViewModel is not suppose to know about the View....
Your ViewModel is a representation of your UI state. You could simply have a IsLoginWindowVisible boolean property exposed, your view can then have code (yes, I said it, view can have code!) that shows / hides a windows based on the state of this property.
I think people stress too much about MVVM. As long as your ViewModel can execute without a view present, in order to facilitate testing, you are doing MVVM correctly. There is nothing wrong with having code to support your view.
I would go simple here and use an event to notify the view it should close.
ViewModel:
public event EventHandler LoginFailed;
public void Login()
{
if (fail)
{
if (this.LoginFailed != null)
{
this.LoginFailed(this, EventArgs.Empty);
}
}
}
View:
((MyViewModel)this.DataContext).LoginFailed += (sender, e) =>
{
// Code to close the window, such as window.Close();
};
You should add a specific event to your ViewModel (something like LoginFailed). Then you should link this event to a command that closes the window. See this blog post on how to link the two.
Here's another option. Instead of using an event you could use a delegate:
public class View {
...
myViewModel.OnFail = () => {this.Close();};
...
}
public class MyViewModel {
public Action OnFail {get; set;}
private void Login() {
....
if (failed && OnFail != null)
OnFail();
}
}

Categories