PRISM + TabControl + Validation = Pain - c#

In my application I have dialogs with mutiple tabs. Im using Prism to register the views with the TabControl.
What I want is a validation for the entire dialog to diable/enable the save button.
The Problem: Currently we have a view-triggered validation. Means every bound item implements the IDataErrorInfo interface. When the View is displayed the binding triggers the interface and displays and error on the UI. The Control has the HasError Property set to true, save button gets disabled.
But the validation does not get tiggered until the view is displayed. Should I move the validation to the ViewModel and validate the Properties on my own or is there a solution to validate inactive views in a TabControl?

There isn't quite enough information to go off of I your question, so I can only guess. First off, you must understand that there are no inactive views in a TabControl. There is only one view in the TabControls visual tree at one time, and that is the selected tab. This means the other views are removed from the visual tree until they are selected. This really doesn't matter though, as validation is controlled via the ViewModel. You ViewModel most likely has a Command bound to your Save button. This command should have a CanExecute defined returning IDataErrorInfo.Error != null (meaning you have no errors). This is where you will check the validity of your objects. Return false if you have any errors, and true if you don't. Hook into the property changed event of your objects, and call the SaveCommand.RaiseCanExecuteChange method to recheck the state of your button.
If each view a tab has it's own ViewModel, hence it's own Save command, I would recommend using a CompositeCommand. This is really an unknown since I don't know how you have architected your dialogs, views, or ViewModels.

Related

WPF Bind different commands to button/menuitem

I would like to ask you for an advice.
The application that I am working on has a docking control and should support working with different "documents". Therefore there can be multiple windows(tabs) opened at the same time.
Each can host a different content. The "documents" that I referred to could be a text file,
an excel style sheet or the main control that this app is being developed for (a geographical data visualization).
I am using the MVVM pattern and MVVM Light library. Note: I have a third party control for the excel spreadsheets.
Now I have a menu bar and a toolbar where I have common menuitems (in menubar) / buttons (in toolbar) like 'save', 'cut', 'copy' etc... When you switch between between the tabs, the 'save' button should call the appropriate save functionality.
The same goes for cut/copy/paste:
When in a tab with text document - cut/copy/paste should operate with text (there are wpf built-in commands for this).
When in the main control - It should work with the graphical elements (I will have to implement these)
When in the spreadsheet - It should work with the enclosed third party commands for the spreadsheet control.
Furthermore, there can be a tab that has some text selected - thus the menuitem/button for cut/copy should be enabled when switched to this tab, while some other tab has no graphical elements selected thus the menuitem/button for cut/copy should be disabled when switched to this tab.
With the save command I can imagine one possible way to do it, but still, I am not sure whether it is a good way to implement it: Have a RelayCommand in MainWindowViewModel
public ICommand SaveCommand
{
get
{
if (_saveCommand == null)
{
_saveCommand = new RelayCommand(() => this.SaveFile());
}
return _saveCommand;
}
}
and the SaveFile() method would call some other 'save method' on the datacontext of the selected tab (which would be a viewmodel for the according "document" type).
However I don't know how to do the enabling/disabling of the save button/menuitem and I am clueless about how to achieve the different cut/copy/paste functionality.
I apologize for the length of the question. Maybe I could have just asked:
"How do you bind different cut/copy/paste commands to the buttons depending on which part of application is selected/active?".
But I felt the added context of what I am trying to achieve would help answer the question.
and the SaveFile() method would call some other 'save method' on the
datacontext of the selected tab (which would be a viewmodel for the
according "document" type).
The SaveFile should be implemented by the ViewModel without going back to the View.
Create several ViewModels to represent different kind of documents and let each implement its Save functionality.
The CanExecute method of a command can be used by the View to decide whether or not the menu item or button should be enabled. All you need is to implement the CanExecute method in the ViewModel. In most cases a Save command's CanExecute would use an IsDirty or similar property.
EDIT
For menu items that should be context/active tab item aware you could create a main ViewModel with the commands for the menu and a collection of ViewModels (one for each tab item)
In the command handlers of the context aware menu items get the active ViewModel and pass the command on.
To get the current TabItem, bind the SelectedItem to a property of the main ViewModel (the type of the property could be a base class of the ViewModels).
That way you do not need to get back to the View to get the current tab item.

SL5 + MEF + PRISM + DataGrid + Edit Rows in Modal Dialog: Is InteractionRequest the Answer?

I am in the process of re-writing one of our large Silverlight apps to use PRISM and the MVVM design pattern.
A very common scenario is a DataGrid in the View. Double clicking a row allows the user to edit the entity represented by the row, using a ChildWindow.
I am tempted just to capture the DoubleClick event in the code behind, create a new ChildWindow of the proper type, and set the DataContext to be DataGrid.SelectedItem.
I know that this is not the proper way to handle this scenario with PRISM and MVVM, however.
I would love advice on what is! (re: my title...it seems like InteractionRequest might be the best way to do this?)
Thanks...
EDIT: We did end up deciding to go with InteractionRequest for our solution. We almost always use "Notification" as the type and pass a new ViewModel (each ChildWindow has its own) as the Content.
In our case the ChildWindow view was complex enough to warrant its own viewmodel. This view isn't too closely coupled with the data grid view.
So, we have an EventTrigger attached to the data grid (we actually use Telerik's data grid) in XAML. The event trigger executes a command in the view model using InvokeCommandAction.
The command publishes an aggregated event that has the selected item as the payload. The event is picked up by the central application controller that is responsible for creating the ChildWindow view and a corresponding view model (using the event payload as the context).
I think that interaction request could potentially be used in your case, but based on my understanding the idea behind an interaction request is a very simple Ok or Yes/No interaction. You might be pushing the boundaries with a bunch of text boxes, validation, etc.

MVVM - Global actions that act on the "currently selected object"

I have a complex application that I am attempting to develop using MVVM (a pattern that I am new to) - the applicaton has tabs and docked windows each of which has the concept of a "selected object", and a global toolbar at the top of the application that has actions on it that need to act on the "selected object".
Imagine a slightly less complicated version of something similar to Visual Studio, for example:
If a pane is selected that contains a list view where the selected object is "inactive" then the "Activate" toolbar item should be enabled. (The global selected item is that list view item)
If however the user then clicks on a tab in another pane which has no selected object then that same toolbar item should be disabled (The global selected item is null).
Ignoring for the moment complications such as multiple selections, at the moment I have implemented this by creating an all-encompassing singleton* model class that represents the "application" itself, e.g.
class MyAppModel : INotifyPropertyChanged
{
public ISelectableObject SelectedObject { get; }
}
I then have "a system" (I admit I'm glossing over a lot of details here) in place for making sure that this property is updated (and the relevent events fired) when changes in the UI results in changes in the global "currently selected object", and the toolbar buttons use this property to determine availability etc...
However I'm getting hung up on the fact that this doesn't seem very MVVM-like (I read somewhere that UI state should be stored in the ViewModel?)
Is having a global model that represents "the application" in this way a good idea? (there are also other properties on there to keep track of other things in the application in a similar way, such as the open documents)
If not, what should I use instead to allow global components (such as items in the toolbar) to find out and keep track of what the "global selected object" is
(*) Which could just as easily be supplied using dependency injection
for MVVM you should definately have a master ViewModel that represents the top-level binding surface for your Views.That master ViewModel will have a 'SelectedItem' property that participates in the INotifyPropertyChanged notifications of the ViewModel. You should then bind your relevant ItemsControl(s) (TabControl etc) SeledctedItem to this ViewModel Property, then other parts of your app can bind to the ViewModels SelectedItem property and bindings will change automatically.
try to register PreNotifyInput event of Inputmanager.current. and register this at applicaiton level this event into global level.
InputManager.Current.PreNotifyInput += new NotifyInputEventHandler(Current_PreNotifyInput);
also refer to Inputmanager class
http://msdn.microsoft.com/en-us/library/ms617136

How to raise property changed events of two user controls in MVVM

in my view, i have two chart controls of type MyChart:
MyChart1
MyChart2
The chart user control has a button called Refresh. Clicking on the button refreshes their item source and they display new data.
In the ViewModel of the view, I have two properties of type MyChart, one for each MyChart.
When I click on the Refresh button, how do I raise RaisePropertyChanged event of the view model of the view?
This is not a correct implementation of MVVM, as you have application logic coded into the View layer.
The standard approach would be to have a Command property on your ViewModel, then bind Button.Command to the ViewModel.Command. This will allow you to handle the refreshing in the ViewModel and give you a place to write any additional code you need to write.
To answer your question, if you are using MVVM, the properties displayed in the View actually exist in the ViewModel, so you should be able to handle PropertyChanged easily enough in the ViewModel using this.PropertyChanged += new PropertyChangedEventHandler(ViewModel_PropertyChanged);

C#: What is the value added by commanding?

When looking into MVC frameworks for flex, as3, silverlight, and wpf... a common concept of ICommand / commanding keeps appearing... Can anyone explain the advantage of using ICommand / Execute() ?
Where I dont see the value added is - Why can't the controller map the input (ie: a click event) to the correct method inside of the model? I'm assuming it is because commanding buys you something - like removing business logic from the controller / the would-be event handler in the controller.
Thx.
Here's a couple of cases that demonstrate the value commands add:
Suppose you have a simple form with a text box and Submit button. You want a button to become enabled only if some text is entered into the text box. With commands all you have to do is to implement CanExecute method (to return true or false depending on the value in a text field) A framework will automagically disable/enable button accordingly. With code-behind (or controller) approach you'd have to write a code do enable/disable button manually.
Suppose later you decided you don't like the button control you used, and decide to switch to a new control (being that a button, or something more exotic) from a different library. All you have to do is make a change in XAML. Any control that supports Command binding will know what to do. In code-behind approach you'd have also modify your button click handler (since new control will probably require different event handler signature)
Suppose later you decide to add a checkbox to your text field that would visually indicate to user whether the content of that field is acceptable. All you have to do is to bind this new checkbox to your command's CanExecute, and now you have two controls already that would automatically change their visual appearance depending on whether form is submittable. With code-behind approach (or controller) addition of a new control would require adding more code.
Suppose you want to test your action. Since commands don't depend on any visual elements, and don't need them, you can easily write a unit test that will not require user clicking any buttons, or entering any text. With controller approach you'd have emulate controller's events, and mock the view.
Summarizing:
Commands provide a well-defined interface between the business logic and the presentation. Business logic implementor doesn't care about how visually certain action (e.g. command) will be implemented. He simply provides the action implementation and an ability for a presentation to query the state of the action. He doesn't care what particular UI element (or elements) will trigger that action, how exactly (in)ability to execute that action would reflect in UI, and what changes UI might go through in the future. At the same time presentation designer doesn't need to know anything about event handlers, controllers, etc. He has a Command and he plugs it in to any UI element (or elements) he chooses without the need to go to C# code at all.
What controller are you talking about?
The Commanding concept in Silverlight and WPF is used to tie together (through binding mostly) the UI to business logic (be it a controller/viewmodel/model/etc).
That is the point, to move the functionality of the command outside of the UI.
Example. Saving a widget in your application is probably always done the same way. Sure, you might let the user change the name, or this or that, but the overall behavior is always going to be the same. Now, in your application you might actually initiate saving a widget through a lot of different UI avenues such as Page 1 has a button on the right hand side that saves the widget on that page, Page 2 has a menu item on the top that saves the widget on that page. The UI is different but the behavior remains the same.
You can accomplish the same goal by using Event Handling (such as grabbing the click event on a button), but now you're back into the context of dealing with UI specific issues. Commanding, arguably, has a cleaner separation.
The simple answer is that commands are bindable whereas events are not. So if you want to respond to a button click event you can either:
Attach an event handler in the code behind.
Create a click command and bind it to the ViewModel's command.
Since one of the goals of MVVM (which is the more common pattern for Silverlight and WPF over MVC) is to seperate code and UI. So if you take the first approach you end up with code in the View. If you take the second approach you can seperate the code from your view using commands and bindings.

Categories