Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have 3 ViewModels, let s say ViewModelA, ViewModelB and ViewModelC.
Each view Model has a corresponding View.
In ViewModelA I have a Public Event that I`m using send some information.
I want ViewModelB and ViewModelC to subscribe to that Event in the current/Running instance of ViewModelA?
How can I do this?
If a new a ViewModelA I will have a different instance of ViewModelA, so I need a reference to the current ViewModelA...
Note: I`m not using MVVM Light or nay other framework (yet), because I did not learn them, yet :)
Thank you.
If you are creating new views from the view of ViewModelA you can pass the reference to another view like this
var viewModelA = DataContext as ViewModelA;
var newWindow = new ViewB(viewModelA);
Then you would need to have a property in your ViewModelB
public ViewModelA MyViewModelA { get; set; }
And in your new view:
public ViewB(ViewModelA viewModelA)
{
InitializeComponents();
var viewModelB = DataContext as ViewModelB;
viewModelB.MyViewModelA = viewModelA;
}
And then you can access your ViewModelA via MyViewModelA.
I've always done it like this and haven't seen any problems so far.
1) You can implement some kind of simple Publisher/subscriber like this one on codeproject. You will be one step ahead because most of frameworks has something similar:
In MVVM light it is called Messenger:
In Prism there is EventAggregator
2) Ugly solution would be to create static event in ViewModelA, this way you won't need a reference
While you can pass references between ViewModels, it makes your app tightly coupled and not particularly scalable. Also if you decide to make a change in the future the amount of refactoring quickly grows making managing changes a lot more difficult.
Have a look at a PubSub Event framework. These are all included in MVVM Frameworks such as PRISM or MVVM-Light that you mention, but you can always add your own version if you don't want or need the full frameworks mentioned above.
Have a look here for a simple no nonsense implementation that you should be able to adapt to your own requirements.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am building an application that has several tabs within the MainWindow view, each containing a couple DataGrids and varying bits of data. I've been researching all week on how to set the DataContext to multiple tables/objects/queries. The only answer I can seem to find from a couple different sources is to create a ViewModel container like so:
class VMContainer
{
public ViewModel1 VM1 {get; set;}
public ViewModel2 VM2 {get; set;}
}
However, I'm unable to find anything that further explains what this is doing. From my perspective, it doesn't seem like there's ever a point where the call for data is being made. Even further, I cannot fathom how to create a call that returns all of the datasets that I need into one object. Can anyone explain how this work or direct me to an article that explains having multiple sets of data as the datacontext of a view?
Edit : How do I return a dataset of datasets?
Thanks.
With a tab control, normally you would see a separate view for each tab's content, and each view would have an accompanying view-model.
A view-model provides the view with the data/properties it needs to display via data binding.
A single view-model can provide many different sets of data. When you mention a dataset, most likely this would be represented in the view-model as a ObservableCollection<T> property.
Here's a simple example of one of those properties using an MVVM framework that implements the INotifyPropertyChanged interface.
private ObservableCollection<MyDataType> myDataSet1;
public ObservableCollection<MyDataType> MyDataSet1
{
get => myDataSet1;
set => SetProperty(ref myDataSet1, value);
}
A view-model can provide many of these properties to the view.
When the view-model is instantiated you would have code that would do the data access and get the data from the database, and you would expose it through your properties so that the view can data bind to them.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
Is it good approach to store all ViewModels in a CoreViewModel in order to provide communication between each other? Or better using MVVM Light framework or something similar? (I want to have no-argument constructors)
public void SetView(Type view)
{
foreach (ViewBase openView in OpenViews)
if (openView.GetType().Equals(view))
{
currentView = openView;
currentView.Reset();
return;
}
currentView = Activator.CreateInstance(view) as ViewBase;
OpenViews.Add(currentView);
}
Ed Plunkett suggests an approach I use, but I'll try to elaborate.
If I have an application that has several sub-controls (say a control per tab page in a tab control) that I want to use then the MainWindow view will bind to the main view's view model in XAML:
<Window.DataContext>
<MainWindowViewModel/>
</Window.DataContext>
The MainWindowViewModel will declare the sub-view models as public properties and in the constructor instantiate and assign a view model object to the property.
Then it is a simple question of binding the data context of a sub-control on to the relevant view model property of the MainWindowViewModel.
<Control DataContext="{Binding ExampleControlViewModel}"/>
Then if a sub-control further breaks down into smaller components, it will declare its own view model properties and the sub-views or sub-controls will bind appropriately. Thus creating a hierarchy of view models that parallel the structure in your view/control hierarchy.
Since the whole tree of view models are initiated from the MainViewModel then it is possible to use Dependency Injection to pass down objects down through the hierarchy. For example, a mediator object to allow messaging between view models or a common database access service class.
If your application opens and closes sub-windows it gets more complicated. How to do that in an MVVM way is beyond the scope of my reply. What is relevant is that you can instantiate a view programatically and inject the view model with something like this:
(new ExampleWindow() { DataContext = new ExampleWindowViewModel(_mediator) }).ShowDialog();
Where _mediator is the object I'm using for message passing between view models.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have extensive WinForms experience, but am new to WPF. Implementing Form design vision through XAML was easy enouhg to delve into, but I'm still a little unclear on what is expected from the M-V-VM programming style. I understand the principle of separating how things look from how they behave, but doing so sensibly in some cases continues to elude me.
For example, if I have a keypad with 9 buttons, and I want a means of enabling/disabling all of them through their IsEnable property, the Form designer in me wants to address them all in a code-behind method targeting them by Design Name. What is the WPF equivalent of such an operation? Am I expected to manage a series of bools in codebehind, and bind each one in the XAML to each respective button attribute? Thanks for any guidance. If this one scenario is explained, it should be sufficient to point me in the right direction
That specific problem is easily solved with binding. You would bind your buttons IsEnabled property to a public Property in your ViewModel and based on the logic contained in your ViewModel when that property value is changed your keypad button would get enabled or disabled.
As #GCamel mentioned you could also have a POCO class that would represent your button which would implement INotifyPropertyChanged interface with one of the properties being the IsEnabled property. You would add instances of this class to an ObservableCollection and when that IsEnabled property changes your button would become enabled or disabled in the UI.
I would also strongly recommend using one of the MVVM frameworks, my personal favorite is Simple MVVM Toolkit by Tony Sneed who also has a great article about the dialogs problem mentioned by #cwap Climb Onboard on the MVVM Message Bus
ideally, you would have an observable collection of button_info with IsEnabled property, icon and text - bind the collection to whathever suitable control like itemsControl, list, or grid and associate your button_info to a datatemple...you see what i mean ? no gui, no gui, just viewmodel and binding
or like this sample ???
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I got this asked in an interview recently . He wanted to know the order of instantiation of Model View and ViewModel what the precise order of instantiation would be ?
I thought the view is always instantiated first and then comes the viewmodel and then comes the model. was i wrong ??
I thought the view is always instantiated first and then comes the viewmodel and then comes the model. was i wrong ??
There is no single standard. There are, in general, two approaches:
View-First - The View will be instantiated first, and in turn instantiate the ViewModel, which will likely create the underlying model. This typically means the order of instantiation is View->ViewModel->Model.
ViewModel-First - The ViewModel is created, which in turn instantiates the Model. The View is generated by the system based on DataTemplates after the ViewModel. This would mean the order of instantiation would be ViewModel->Model, then View (indirectly from XAML).
Most frameworks which are geared heavily towards a designer-first approach tend to do View-First construction. This makes it easier to work with the designer (in general).
Many frameworks which are geared heavily towards developer-focused scenarios will often do ViewModel first. This approach can actually lead to even less coupling, and simpler "code-only" construction of everything from the ViewModel level.
This is an open ended question because you can look at it conceptually, in which case it follows the acronym. If you look at it in practice (particularly referring to WPF or WinStore Apps) its a bit different.
Conceptually
Model should be instantiated first because all ensuing decisions of the application will be based on the model on which the app was designed to operate on. Then the view model, because views depend on view models, not the other way around. One VM can have multiple views, but one view generally does not have multiple view models (generally!). Then the view(s) that present the data.
Practice (In WPF and WinStore Apps)
The App class is instantiated first, which fits in some odd portion of the VM-M area. But that's not completely relevant because it's outside the scope of the pattern. The View is usually created and attached to the visual tree first. Then the ViewModel is instantiated in the code-behind, at which point the model is loaded. Then a massive UI refresh occurs that displays everything that was loaded initially. From then on out, everything in the 'conceptually' portion holds true.
This question may get closed due to opinions, as there is no definite answer. but this is what I've seen, read, and experienced.
Well that's a strange interview question. In my opinion and in general, I would agree with you. The view model would instantiate the model and the view would come first, instantiating the view model. But of course, it very much depends on the architecture of the application. The beauty of WPF enables these things to be done in different ways. Then you also have dependency injection, so I would say that the answer should really be 'it depends'.
The question is a bit silly, because it's limited to a simple scenario where each layer is a single class. Suppose one view model provides another one. If we decide "view comes first", do we need to create another view before we are allowed to call that function on the original view model? What if the view must be chosen based on the returned view model? And on the flip side, if we decide "viewmodel comes first", what if the new viewmodel must be chosen based on parameters input from the view?
A layered architecture is about dependencies. MVVM says V depends on VM and VM depends M. It doesn't say anything about instantiation order. You might decide that dependencies should be passed into constructors, meaning that instantiation order needs to be M-VM-V, but I don't see any practical reason to try to enforce such a small detail throughout an entire application
IMHO it is a Trojan horse question to see how one thinks more than an actual answer to see if one can quantify their experience with actual MVVM projects.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I'm beging to work on a re-design (software design) of XAML-based application, I wrote 2 months ago. I think I made lot's of architectural mistakes during development, which led to situation when the UI part of app is hard to extend, maintain, code is hard to understand. My app is written using PRISM 4 in MVVM style, but despite the fact that Prism was invented for modular design my App turned out to be very monolithic. I'm going to continue to use PRISM 4 in new design, but this time I want to break my UI part of application in smaller, reusable, extendable building blocks.
Suppose we are designing data input form.Top container contains Save,Cancel buttons and TabControl, which contains 2-3 tabs that contain lot's of grouped input controls.
The are 2 completly different aproaches to UI design I can see: static (compile-time), dynamic(run-time). Static it's when you predefine your UI before compiling, i.e DataGrid with columns defined in XAML. Dynamic it's when you compose UI at runtime, i.e you defined DataGrid in XAML but add columns at runtime based on user asctions.
What rules you use when you decide which aproach to use, sattic or dynamic? What you would choose in this particular example?
Next big question is how to break UI to pieces.
What rules you use when you define UserControls, how you would define UserControls for this example form? Now about ViewModels, would you create single VM for this example form or multiple (explain)? What do you think about situations when ViewModel contains other ViewModels (not simple wrapers around model, but real VM which contains logic).
And now the hardest question at least for me. Extending UI building blocks (UserControls and ViewModels).
Situation when you need to create a copy of some Form but with slightly different interface and|or logic is quite often, especially when you need to integrate authorization (permissions) in UI. Suppose we need to support slighly different version of out example form (doesn't matter how many exactly versions, suppose 2-6).
I can think of these aproaches to solve this problem:
Create duplicates of whole from (usercontrols and viewModels) and modify them (the static way). The good thing all variants are independent, great flexibility, no dependecies, the bad thing code duplicate, if you will need to change something in all variants most likely you will have to modify this everywhere, especially with ViewModels.
Conditional presentartion, you add lot's of conditional code to your ViewModel, like IsThisVisible, IsThatDisabled (the dynamic way). The good thing maximum code reuse, the bad thing code bloat and mess. Your code will be hard to understand,maintain.
Break UI to very small atomic UserControls, compose separate form variants from this UI pieces, and use ViewModel inheritance with virtual members and overrides. I haven't ever used inheritance of ViewModels, and would like to hear your opinion on this subject.
n. Other aproaches I can't think of.
In my experience, the development path tends to work this way:
Design a view in Blend or Kaxaml or whatever, and a view model that backs the view.
Realize that portions of the view need to be dynamic. Implement flags in the view model and styles in the view to show/hide them.
Realize that all the flags are getting out of hand. Get rid of the flags, and refactor the view to present collections of user controls, and the view model to dynamically populate collections of view models.
It sometimes happens that I know well in advance that I'm going to need to use approach #3, and I design for it from the start.
But one of the beauties of WPF and MVVM is that even if I don't design for this from the start, it's not too hard to move in that direction if circumstances demand it. Refactoring a bunch of view model properties into a single collection of view models doesn't take a whole lot of time or effort once you've done it a few times.
I can tell you this, though: making a copy of a XAML object and editing it makes klaxons sound in my head. It's possible to imagine circumstances under which that might be OK, but it's not the way to bet.