Have multiple views in one Window (MVVM) - mvvm

I'm trying to learn MVVM and as a new person without a tutor, sometimes it gets sooo confusing. right now I have this problem:
** in one window, I have used 3 different views from different modelviews.
** each view is for selecting one item from a branch and we will traverse the tree.
** in first View, I choose my book
** the 2nd view will show pages of that book
** the last view I want it to show exercises of that page.
so far I was able to bind the 1st view to the Books. now, how should I bind the second view's source to the 1st one's slectedItem ?
MVVM Problem http://clickasun.ir/8283kitchen/images/mvvmproblem.jpg

there are several ways to achieve what you want. eg.
public class Exercise{}
public class Page
{
public List<Exercise> MyExercise {get;set;}
}
public class Book
{
public List<Page > MyPages {get;set;}
}
viewmodel
public ObservableCollection<Book> MyBooks {get;set;}
xaml
<ListBox x:Name=books ItemsSource="{Binding MyBooks}"/>
<ListBox x:Name=pages ItemsSource="{Binding ElementName=books,Path=SelectedItem}"/>
<ListBox ItemsSource="{Binding ElementName=pages,Path=SelectedItem}"/>
this is of course just one way to do it.
ps: code handwritten, so check for errors

OK I want to thank anyone who read this and tried to help, Specially yo guys "Blindmeis, Jen H"
thank you.
I know this scenario had to be so general, I just couldnt find it.
so I found 2 approaches to it that both can be good solutions.
Use Microsoft Prism. (Its a pattern to make modular programs in WPF with ease)
MSDN LINK
Another LINK
Use Master Detail Pattern
Here it is clear
So I got mine solved. Hope it would be useful for you too.

Related

Use eclipse GMF to create read only diagram

I followed the file system example http://gmfsamples.tuxfamily.org/wiki/doku.php?id=gmf_tutorial1
what I wanted to do is not using the generated editor with its palette.
I created a new plugin with one view and I wanted to create a diagram programatically inside this view to show for instance 2 objects connected with link
I came across this answer GMF display diagram example
but it didn't help me a lot.
in createPartControl of my view I did
#Override
public void createPartControl(Composite parent) {
DiagramGraphicalViewer viewer = new DiagramGraphicalViewer();
viewer.createControl(parent);
RootEditPart root = EditPartService.getInstance().createRootEditPart(diagram);
viewer.setRootEditPart(root);
viewer.setEditPartFactory(new EcoreEditPartProvider());
viewer.getControl().setBackground(ColorConstants.listBackground);
viewer.setContents(diagram);
}
as in the answer but I didn't know how to get that "diagram" variable
The easiest would be use the same GraphicalViewer for your view and the same diagram as well. Just get your DiagramEditPart from the viewer and call disableEditMode() on it. (Do the appropriate type casting if necessary).

How do i add a custom made TinyMCE form element to my Zend Project?

I have been working with Zend for a few months now and am at a stage where i'd like to add some fields to my form using TinyMce. What i want to achieve is to be able to just create a form extending Zend_form and just be able to say
$element = new TinyMce_Form_Element_Editor('element');
But i just do not have a single clue on how to achieve this. I have of course been looking around before asking this question and most sources just point me towards this site.
Wich seems to be aimed at people with alot of experiance with Zend. 2 months in it's not a big surprise i am not at the level this might have been intended for as i have tried following the instrucutions given and creating the file setup as shown by in the svn repositiry create by the writer of this article.
Aside from heading from one error into another i also do not uderstand what the code is doing exactly, i just have a vague guess at best when i run trough it.
Is there any kind of easy to follow simple tutorial explaining how to enable tinymce in a Zend Form?
Any advice or tips on how to achieve my goal will be well appreciated
Not best solution but you may find it useful:
class My_Form_Element_Tinymce extends Zend_Form_Element_Textarea
{
/**
* Element CSS class name
* #var string
*/
protected $class = 'tinyMCE';
public function init()
{
$this->getView()->headScript()->appendFile('path/to/tinymce.js');
$this->getView()->headScript()->appendFile('path/to/tinymce_config.js');
}
}
and in your tinymce_config.js add selector for tinyMCE class name
tinymce_config.js is your tinyMCE configuration file if you never used tinyMCE goto http://tinymce.com and you will find many examples with what you need.

Handling many similar ICommand implementations?

I am working with MVVM and encounter the following problem with the use of many similar commands.
I wanna make many buttons which is used to show the books of different categories.
The model is some data about a book, say,
class book
{
string name;
string author;
.....
.....
string category;
}
A list of book is stored. A GUI is used for the user to view the books with different categories. Therefore, buttons for each category is created. For example:
Buttons:
Comic
Social
Academic
Science
Leisure
Political
Cartoon
Gambling
Magazine
All
There are about 10 buttons that I have to created. (9 categories, 1 for viewing all)
In MVVM, each button has its own command. From that, there would be 10 commands in the ViewModel. However, the coding 9 of its are very similar with the only difference in the category.
So, I would like to ask if there is any suggestion/methods to make it more code-saving?
I do have an idea. That is to combine all the commands into one. However, this method required the View (Xaml) to pass a CommandParameter in each button to the one command in order to distinguish the different category. This will make the XAML more complex and increase coupling level with the ViewModels/Business logic.
So, would there are more concise way?
You can use DelegateCommand from Microsoft.Practices.Composite.Presentation.dll and use CommandParameter
<Button Command="{Binding bookCmd}" CommandParameter="Comic">
<Button Command="{Binding bookCmd}" CommandParameter="Music">
<Button Command="{Binding bookCmd}" CommandParameter="News">
private DelegateCommand<string> _bookCmd;
_bookCmd= new DelegateCommand<string>(ExecuteBookCmd);
private void ExecuteBookCmd(string category)
{
//Have fun
}

ASP MVC 2 Pattern for implementing CanExecute style commands

I have come from WPF (MVVM) background and trying to shift to MVC 2. Is there any pattern in MVC2 where you can use Commanding/Command buttons like <input> which you use to submit the form so that you can hide/disable when you try to Render the View.
In MVVM world, your commands could implement ICommand interface, and it had CanExecute method which was quite useful. I was wondering if there is anything similar in ASP MVC 2 ?
The only way I can think of, is to do it in the View, so that I can check the flag on ViewModel (CanSave) and depending on that show/hide the <input> tag.
Basically I want to have 2 version of the website running, one in Read-Only mode and the other Editing mode.
Let me know if you need any clarification.
ASP.NET MVC does not feature the notion of 'controls', as are found in classic ASP.NET and WPF. The foundational blocks of ASP.NET MVC are HTML elements, like <input>, <button> et cetera. Naturally, these don't offer the functionality you're looking for (i.e. Implementation of the ICommand Interface).
The scenario that you're looking at (i.e. two modes of your form) can be (and arguably should be) dealt with at the View level. You're already facing the right direction: have a 'CanSave' property on your Model, and use this in the View to determine what is generated.
Example:
<% if (Model.CanSave)
{ %>
<p>First Name: <%= Html.TextBox("firstname", Model.firstname) %> </p>
<% }
else
{ %>
<p>First Name: <%=Model.firstname %></p>
<% } %>
You'll probably want to check out the DisplayTemplates and EditorTemplates... very handy for this scenario. Brad Wilson does a good job here.
It will help you move to this:
<%= (Model.CanSave) ? Html.EditorFor(x => x.firstname) : Html.DisplayFor(x => x.firstname) %>
...which makes your View clean and nice.
If you can't get MVC to do this it's relatively worth it to hand-code something like this vb-style pseudocode. This involves...
Subclassing your controls.
Not as much of a pain as it sounds, but, it is a medium sized one. Therefore it is only appropriate for medium-sized to large apps. But worth it for them.
Interface BaseUIControl
Property Enabled as Boolean
Property Visible as Boolean
Property Name as String
Property EntireStateAsXML as string ' You can use this to do EVERYTHING!
Interface UserActionItem
Event Clicked(sender as UserActionItem ... don't pass anything from UI namespaces!)
Class MyButton (or link, etc.) Implement BaseUIControl, UserActionItem Inherits UI.Button
How does this help? You've basically replaced the missing functionality. Your Controller (or even application layer) can be aware of the UI components by interface only, so they won't have to see the UI types.
more...
You can leverage this philosophy to control everything. This has saved me thousands of hours of monkey code.
Interface TextControl
Property Value as text
Interface CheckControl
Property Checked as boolean
The above two are Pretty basic - you inherit MyCheckBox and MyTextBox from the UI versions and implement the appropriate.
Of course you could set up common code to loop thru all controls and auto-validate (or loop thru and get each one's XML to autobind the whole form).
Interface ValidationBase
Property Required as Boolean
If you have a text or numeric-only mask or restricitons built into 2 subclasses...
Interface ValidationNumeric
Property MinVal, MaxVal as double
Interface ValidationText
Property MinLen, MaxLen as double
No, it won't go to the database for you. But this sweeps a ton of crud under the rug.
You can even set these property values in the UI designer - yes, putting BL in bed with UI, BUT, if you only have one UI for the BL, actually works very well.
Now image a UI with a mix of things like listbox/multiselect, double-list picker controls, checked listbox, a groupbox of option buttons/checkboxes ...
Interface Selector
property Items as list (of string)
property SelectedItems as list (of string)
Use what works on the UI - your generic routines can care less what they look like!! The subclassed UI pieces will just implement them to set/get the right values.
In addition ... we added 'validationEquation', ActivatesEquation (gray/ungray), SetValueTriggerEquation (if true, set value to SetValueEquation, otherwise, leave alone), which allowed controls to be set to simple values from other items (basically getting the values from bound objects as if using reflection) via Pascal Gayane's Expression Evaluator (it reads .net types!)
You can also subclass the main form, have it recurse thru all it's subcontrols, put together the XML's for the whole screen, and serialize it like that. You can have your own classes implement these in the non-UI layers and use it to totally (de/)serialize the UI state, and use them to read the UI too, if they relate to a business object, to map to it.
It's unbelievable how much this simplifies a complex app. We have one with 1200+ data entry panels (... pages... ours is a thickclient app) that will fill out 250 different paper forms at 250K LOC. The form definitions contain the 'name' of each control and this is pulled from the XML generated from the screens. We probably saved 500K LOC as many of the screens have no code behind them or only trivial code; all the databinding, validation, etc. is handled by common routines that reference the interfaces.
Like I say, this only works for a big app. Spend at least 2-3 weeks developing 90% of the functionality, though; probably another month throughout the 2 years dev maturing it. I am guessing your apps is big if you're caring about ICommand and its conveniences. I would put the payback at 15-20 moderately complex pages.
If I'm understanding the question correctly, you could write a ControllerCommand class to encapsulate this. Something like this:
public class ControllerCommand
{
public string Action { get; set; }
public string Controller { get; set; }
public object RouteValues { get; set; }
public bool IsEnabled { get; set; }
}
Your Details viewmodel might use it like this:
public class DetailsModel
{
public guid Id { get; set;}
// some other viewmodel properties
public ControllerCommand Edit { get; set; }
}
You could write extension methods on HtmlHelper to replace the built-in ones:
public MvcHtmlString CommandLink(this HtmlHelper html, string linkText, ControllerCommand command, object htmlAttributes)
{
if (command.IsEnabled)
{
return html.ActionLink(linkText, command.Action, command.Controller, command.RouteValues, htmlAttributes);
}
else
{
return MvcHtmlString.Create(linkText);
// perhaps return <span class="disabled-command">linkText</span>
}
}
One of the ways I have found is to use Filter attributes which you can put in your Actions, but that only handles CanExecute on the server side.
For the GUI side, couldnt find better way than putting If statements to check if the user is Priviliged to run particular action (i.e. Edit/Delete buttons)

Sort ItemsControl Prism v2.2 Region without a bound collection?

Is there a way to sort the views that get added to a ItemsControl region? The views being added are registered with the container and added to the region in each unique module.
Some pseudo code...
Shell:
<Window>
<ItemsControl Prism:RegionManager.Region="ItemsRegion"/>
</Window>
Modules: This is the initialization code in the modules.
protected override void RegisterViewsAndServices()
{
CommonContainerLifetimeManager.Register<IView, ItemView1>();
Container.RegisterType<IViewModel, ItemViewModel1>("ItemViewModel1");
}
public override void AdditionalInitialization()
{
var itemView1 = Container.Resolve<ItemView1>();
RegionManager.Regions["ItemsRegion"].Add(itemView1);
}
With this approach it is showing the added views in the shell's itemscontrol in the order the modules are loaded. Based on the role of the logged on user different modules are loaded. Is there a way, without having to add a collection inbetween, to sort the itemscontrol.items on a property of the view's viewmodel for example? Is there a way to force the modules to be loaded in a certain order? I am currently using a module catalog.
Thanks
Andy
So I found the answer to this question... At least I found the answer in Prism v4.
You add a ViewSortHint class attribute to the View's code behind. Prism will find this attribute and sort the views based upon the string you enter in the ViewSortHint parameter.
[ViewSortHint("01")]
public partial class SortedButton : UserControl
{
public SortedButton()
{
InitializeComponent();
}
}
Hope this helps someone...
Andy