Conditionally auto-click button in MVVM using xaml - c#

I am writing an application based on MVVM architecture. The application has a Wizard like workflow. In couple of pages (views) in my application, I need a button to be auto-clicked when a certain condition is satisfied. The views are tied together using the root Wizard view model which has a ClickNextBtn command that is tied to the Next button in the root Wizard view. So, I need something like in the root Wizard view:
<DataTrigger Binding="{Binding Path=CanAutoClickNext}" Value="True">
<Setter Property="ClickBtn" Value="true" />
</DataTrigger>
The property in the above sample is meaningless, but hopefully it helps convey what I am trying to do.
The CanAutoClickNext bool property is available off of the Wizard view model.
On one of the views where I need the Next button auto-clicked, I tried passing the WizardViewModel as an argument to its corresponding view model's constructor when it is first instantiated in the root wizard view model, and then calling the ClickNextBtn off of it in a method therein later when the view is actually loaded. But that did not work, not surprisingly.
I know how to programmatically click a wpf button, but getting it all tied together in the framework I have is proving to a big challenge. Any feedback is appreciated.
UPDATE:
I ended up rewriting the UI design pattern (still MVVM) so that now instead of having to having to move to a next page automatically, the state within a page changes and a different set of controls become active. Users are then prompted to click next.

Like the comment's on your question stated, this should be a concern of the ViewModel to invoke the Click Handler.
How you could go about implementing this is very similar to something like this Question's answer
Now in MVVM, you should have your Button's connected to an ICommand in the ViewModel(If your using MVVM Light toolkit, it will be RelayCommand/RelayCommand<T>).
Now assuming this ICommand variable in your VM is called NextButtonCommand,
what you can do is
public bool CanAutoClickNext {
get {
return _canAutoClickNext;
}
private set {
if (value == _canAutoClickNext)
return;
_canAutoClickNext = value;
RaisePropertyChanged(() => CanAutoClickNext);
if (_canAutoClickNext)
NextButtonCommand.Execute(null);
}
}
with this, when your property in the VM CanAutoClickNext gets set to "True", the Execute function of the ICommand is automatically invoked by the VM. This seperates all the logic handling to the VM and keeps the View dumb as what is recommended by MVVM when it comes to application / business logic.
Side Note
The property CanAutoClickNext seems a waste if it's not being bound to anything from the View. If this is the case, I'd recommend just getting rid of that property and invoke the ICommand.Execute(null) from the place where the logic holds fit than use a property with INPC just for this case.

I'll follow up from a different angle. Let's say you have any message bus ready (IEventAggregator, IMessenger, doesn't matter). I'll use the Caliburn.Micro's IEventAggregator along with the nomenclature 'cause that's what I'm most familiar with. Now you might have a very simple event:
public class MoveNext
{
}
Then your 'host' viewmodel of the wizard:
public class WizardHost : IHandle<MoveNext>
{
private readonly IEventAggregator messageBus
public WizardHost(IEventAggregator messageBus)
{
this.messageBus = messageBus;
this.messageBus.Subscribe(this);
}
/here you might have the 'real' command method, e.g:
public void GoToNextQuestion()
{
// do stuff
}
public void Handle(MoveNext message)
{
GoToNextQuestion();
}
}
public class WizardPage
{
private readonly IEventAggregator messageBus;
private bool shouldMoveToNext;
public WizardPage(IEventAggregator messageBus)
{
this.messageBus = messageBus;
}
public void DoStuff()
{
//at some point, you might want to switch the flag or do whatever you need/want to do and:
if(shouldMoveToNext)
messageBus.Publish(new MoveNext());
}
}
Now when you DoStuff() in your wizard page, you can publish the event and the 'host' page will react and flip the page.
That's of course all nice if you're using any MVVM framework that's out there. MVVM Light has the Messenger, Caliburn.Micro has - as you might have noticed - IEventAggregator.

Related

How to perform View navigation using MVVM? Win RT

I've started a Windows Universal project following the MVVM pattern, and came to the situation where I need to navigate to another page with a button click.
Normally I would do this in code behind using the button's click event like the below:
private void AppBarButton_Click(object sender, RoutedEventArgs e)
{
// Navigation Without parameters
this.Frame.Navigate(typeof(SecondPage));
}
But since I need to follow the MVVM pattern with this app, I'm wondering how should I set up the navigation to a new View on button click?
I've come across ICommand for this task in WPF solution after a Google search, but not 100% on how it should be implemented for this Windows Universal Framework.
Basically you got two options
1. use a navigation service
You can define an INavigationService interface and pass it to all your ViewModels in your viewmodel assembly (assuming you are using different assemblies which is important to keep ensure you are not referencing to the view from your viewmodel and hence violate MVVM pattern).
public interface INavigationService
{
void Navigate(string page, object parameter);
}
In your viewmodels you can simply call it with navigationService.Navigate("UserEditPage", selectedUser.Id);.
Implementation could be as simple as
public class WinRtNavigationService : INavigationService
{
public void Navigate(string page, object parameter)
{
Type pageType = Type.GetType(string.Format("YourCompany.YourApp.ViewModels.{0}", page));
((Frame)Window.Current.Content).Navigate(pageType, parameter);
}
}
You use this, if you have the need to navigate from ViewModels.
2. use behaviors
You can use behaviours to add reusable navigation support to XAML directly, hence completely avoiding the code behind.
For this, Blend offers Interactivity Triggers and a NavigateToPageAction behavior.
<Page
xmlns:i="using:Microsoft.Xaml.Interactivity"
xmlns:c="using:Microsoft.Xaml.Interactions.Core" >
....
<Button Content="Edit">
<i:Interaction.Behaviors>
<i:BehaviorCollection>
<c:EventTriggerBehavior EventName="Tapped">
<c:NavigateToPageAction TargetPage="YourCompany.YourApp.ViewModel.UserEditPage" Parameter="{Binding Path=SelectedUser.Id}" />
</c:EventTriggerBehavior>
</i:BehaviorCollection>
</i:Interaction.Behaviors>
</Button>
...
</Page>
Blend Behaviors/Interaction Triggers are generally used to bind navigation functions to Buttons or other UI elements (i.e. click on a picture which doesn't have to be a button), as it doesn't require any code within the Code Behind or ViewModel.
If a navigation is to occur after some validation, i.e. you have a multi-page form for user registration and you have a "Send" Button binded to a RegisterCommand and the RegisterCommand does an online validation and you're required to go back to previous page, you'd want to use the INavigationService.

When to separate View from ViewModel?

So I'm working on a GUI and most of it I implemented with 1 window and used the code-behind for that window to handle most of the logic. The program is very GUI driven. Say there is a combo box, if you select something from the combo box, the data drastically changes and all the other GUI boxes/labels/grids change or clear ect ect.
I'm doing a lot of refactoring and I've been aware of MVVM, but I've never really seen the need for it. I understand what and why its used, but functionality its just easier to reference all the GUI components straight from the code behind I've found.
For example...
In my main window I have
<ComboBox x:Name="MyTitlesUI" ItemsSource="{Binding Titles}" SelectionChanged="MyTitlesUI_SelectionChanged">
So the ComboBox is tied to a List Titles in my MainWindowViewModel right?
Where should MyTitlesUI_SelectionChanged event go? It needs to go in the View correct? But what if the functionality of SelectionChanged has to do with data inside MainWindowViewModel?
Say you change the selection in MyTitlesUI and now the program has to look up up that Title string in a database. All of that database functionality is in DBClass which you declare in MainWindowViewModel. How do you access that functionality? Why would you have to do this:
In main window cs:
private void MyTitlesUI_SelectionChanged(object sender, EventArgs e)
{
viewModel.ConnectToDataBase((string)MyTitlesUI.SelectedItem);
}
In MainWindowViewModel.cs
private SelectedTitle;
public void ConnectToDataBase(string title)
{
SelectedTitle = title;
DBClass myDB = new DBClass(SelectedTitle);
.... //do stuff with myDB
}
That just seems kind of unnecessary no? This is just a mild mild example of course and maybe that seems pretty clean. But if you're doing really complex back and fourth between View and ViewModel, the reference to MyTitlesUI.SelectedItem in View may be needed in ViewModel for other functions to work hence the SelectedTitle private variable.
Now you have more assignments, more variables, more functions that just call other functions than just a simple MyTitlesUI.SelectedItem to deal with.
Why not bring the DBClass reference up to the View or similar?
Especially if you're doing a lot of UI manipulation that the information inside your ViewModel will be playing with. Say once I change the selection of Title, I need graph to clear. But my graph can't clear until my ViewModel has connected to the DB or something.
I'm going to have graphs or grids defined in my View that depend on dynamically created data in my ViewModel that needs to update. And I'm trying to wrap around what needs to be in View and what needs to be in ViewModel. It seems to be not proper to reference View from ViewModel, so something like MyTitlesUI.SelectedItem can't be called in ViewModel.
EDIT:
So going back to the Selected Item example, say I have a Treeview UI item. I want to bind that to a Treeview that I don't have yet. I create the data for it procedural with DB connect. So the user selects from the combobox the Title they want. Db Connect then creates, asynchronously, a TreeviewItem in some kind of data structure.
private SelectedTitle;
public void ConnectToDataBase(string title)
{
SelectedTitle = title;
DBClass myDB = new DBClass(SelectedTitle);
if(myDB.doneWorking)
{
myTreeView.ItemsSource = myDB.GetTree();
}
}
but functionality its just easier to reference all the GUI components
straight from the code behind I've found
Wrong. MVVM delivers a clean, Property-based approach that's much easier to work with than the txtPepe_TextChanged() winforms-like approach. Try to change the Text for a TextBlock buried deep inside a DataTemplate that is used as the ItemTemplate of a Virtualized ItemsControl using code behind... WPF is not winforms.
Where should MyTitlesUI_SelectionChanged event go?
Nowhere. MVVM works best with a property/DataBinding based approach, as opposed to a procedural event-based approach.
For instance, a ComboBox-based UI that "does stuff" when the user changes the selection in the ComboBox should be defined like this:
<ComboBox ItemsSource="{Binding MyCollection}"
SelectedItem="{Binding SelectedItem}"/>
ViewModel:
public class ViewModel
{
public ObservableCollection<MyItems> MyCollection {get;set;}
private void _selectedItem;
public MyItem SelectedItem
{
get { return _selectedItem; }
set
{
_selectedItem = value;
NotifyPropertyChanged();
DoStuffWhenComboIsChanged();
}
}
private void DoStuffWhenComboIsChanged()
{
//... Do stuff here
}
}
Now you have more assignments, more variables, more functions that
just call other functions than just a simple MyTitlesUI.SelectedItem
to deal with.
Wrong. What you have now is a Strongly Typed property in the ViewModel of type MyItem that you work with instead of the horrible casting stuff (MyItem)ComboBox.SelectedItem or things of that sort.
This approach has the additional advantage that your application logic is completely decoupled from the UI and thus you're free to do all sorts of crazy stuff on the UI (such as replacing the ComboBox for a 3D rotating pink elephant if you wanted to).
Why not bring the DBClass reference up to the View or similar?
Because DataBase code does NOT belong into the UI.
Especially if you're doing a lot of UI manipulation
You don't do "UI manipulation" in WPF. You do DataBinding which is a much cleaner and scalable approach.

MVVM when to create a viewmodel for a control?

Or should I only create viewmodels for the domain data being represented? While reading on MVVM, I came across this:
"The ViewModel is responsible for these tasks. The term means "Model of a View", and can be thought of as abstraction of the view, but it also provides a specialization of the Model that the View can use for data-binding. In this latter role the ViewModel contains data-transformers that convert Model types into View types, and it contains Commands the View can use to interact with the Model. "
http://blogs.msdn.com/b/johngossman/archive/2005/10/08/478683.aspx
If the viewmodel is a model of the view, then doesn't it make sense to put properties of the view in the viewmodel rather than on the code behind of the view itself?
I guess in making a custom control I just have a hard time deciding when I should just add a property to the control's code behind and when it is worthwhile to make a viewmodel for the control to represent it. Honestly I kind of feel that moving all of the control's view related properties to the viewmodel would clean up the code behind of the control leaving only the control logic.
However, if I were to change things like this, then at times when an item needs properties from the control itself I can no longer use {Binding ElementName = control, Path=property} and have to instead get the data context of the parent (because the current datacontext would be on the individual subitem of the observable collection.
Basically I was considering whether I should move properties from Class GraphViewer into a GraphViewerViewModel and then just bind to it.
Code is worth a million words so:
public class GraphViewerViewModel :DependencyObject
{
private const int DEFAULT_PEN_WIDTH = 2;
private const int DEFAULT_GRAPH_HEIGHT = 25;
public SignalDataViewModel _SignalDataViewModel
{
get;
set;
}
public PreferencesViewModel _PreferencesViewModel
{
get;
set;
}
}
Meanwhile
public class SignalDataViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
ObservableCollection<SignalViewModel> _signals;
public ObservableCollection<SignalViewModel> Signals
{
get
{
return _signals;
}
private set
{
_signals = value;
}
}
ObservableCollection<SignalViewModel> _AddedSignals;
public ObservableCollection<SignalViewModel> AddedSignals
{
get
{
return _AddedSignals;
}
private set
{
_AddedSignals = value;
}
}
it is a pain to type:
PenWidth="{Binding RelativeSource = {RelativeSource AncestorType={x:Type DaedalusGraphViewer:GraphViewer}},
Path = _GraphViewerViewModel._SignalDataViewModel._AxisDivisionUnit.GraphPenWidth, Mode=OneWay}"
and I'm wondering if it is worthwhile to make the change or whether I'm misunderstanding what a view model should be used for in mvvm.
I guess in making a custom control I just have a hard time deciding when I should just add a property to the control's code behind and when it is worthwhile to make a viewmodel for the control to represent it. Honestly I kind of feel that moving all of the control's view related properties to the viewmodel would clean up the code behind of the control leaving only the control logic.
In general, a custom control is 100% View layer code. As such, it really falls outside of MVVM entirely.
The main goal when making a custom control to be used within an application being designed with MVVM is to make sure that you design and build the custom control in a way that it is fully compatible with data binding. This will allow it to be used within your View layer of your application exactly like other controls.
As such, this pretty much guarantees that you'll have code behind, since implementing Dependency Properties really requires code behind. You also don't want to set the DataContext of a custom control within the control (since you want to inherit the data context of the user control or window using the control).
Basically I was considering whether I should move properties from Class GraphViewer into a GraphViewerViewModel and then just bind to it.
If the types are specific to your domain, then this is really typically more of a UserControl being used by your application. In that case, creating a ViewModel and just binding is likely good.
If this is, on the other hand, a true custom control that's made to be completely general purpose (ie: usable by anybody in any application), then keeping it as a "pure view" custom control typically means that you 1) won't take a dependency on any ViewModels or domain specific objects, and 2) not set the data context (which means no view model).

ASP.NET MVP Pattern

I'm trying to implement the Model-View-Presenter design pattern in my application.
The general concept of the MVP pattern is known for me, but I'm more struggling with getting it done using nested usercontrols.
I've got a few possible scenarios I might be able to implement, but before doing so I'd like to hear your opinion.
I think it does not matter to post any of my code, since its more a "concept" I'm trying to understand.
So the scenario is:
1 page used to connect 2 user controls. One of these usercontrols contains a child usercontrol. How do I work around with MVP pattern in this case?
1 Page
1 UC
1 UC
1 SubUC
Edit:
So basicly what I want to know is how we can interact between two views (parent and child) using MVP in both usercontrols.
I'll show you an example in ASP.net WITHOUT MVP:
http://pastie.org/5452134
Now with MVP, do we still register to this kind of event using the CodeBehind? Knowing that this parent and child usercontrol would both be using the MVP pattern. Or does the presenter get's included in this interaction?
Eventually I can change the code to:
http://pastie.org/5452180
But I'm wondering whether this is OK, considering the MVP pattern...
Or do we more need an approach like this:
http://pastie.org/5452174
All the above examples are written in the CodeBehind of the parent view. Is one of this correct? If not, how can we achieve this using a better approach
Edit 2: I've added a solution with my example approach at: https://github.com/frederikprijck/ASP.NET-MVP
I think this should be pretty much what I wanted...
I don't see a problem - user control is nothing but a view. And a presenter can interact with multiple views at a time. So in this case, your presenter can have reference of say 4 views (one for page, two for user controls and last one for sub-user control).
Alternatively, you want to have single view per presenter and in such case, you can see user control as child view of the parent view(page) and so parent view need to bubble up and down view interactions meant for presenter. However, I would prefer the earlier approach where presenter handling interaction multiple views.
See this related question on SO on how wiring is done: https://softwareengineering.stackexchange.com/questions/60774/model-view-presenter-implementation-thoughts
Finally, you may want to look at MVVM pattern which I believe works great for compositional UI. Instead of presenter, you will have view model that will control the interaction between view and model - however, unlike presenter, view model does not know about view - rather view observes (and updates) view model to render itself. See this article here (View Model is referred as Presentation Model): http://www.codeproject.com/Articles/23340/Presentation-Model-in-Action
EDIT:
To be honest, I don't prefer any of your approaches. I like MVP implementation where presenter holds reference to view via interface (no tight coupling) and view does the wiring i.e. creates presenter instance and inject the view references. The presenter listens to view events and call methods on view. View never calls directly on presenter's methods. (Other variations of MVP are possible - see the SO answer that I had sought). With this, I will explain two approaches that I had explained earlier.
Approach 1:
Each user control is an independent view. There will be common presenter that will handle multiple views. For example,
public class Presenter1
{
IView1 _view1;
IView2 _view2;
public Presenter1(IView1 view1, IView2 view2)
{
_view1 = view1;
_view2 = view2;
_view1.OnSave += OnSave;
_view1.OnSomeEvent += OnSomeEvent;
_view2.OnFoo += OnFoo;
}
public void OnSave()
{
var data1 = _view1.GetData();
var data2 = _view2.GetData();
// update model
...
}
public void OnSomeEvent()
{
// inform view2 about it
_view2.DoOnSomeEvent();
}
...
}
public partial class MyPage : Page, IView1
{
public void Page_Load(...)
{
//do wire up
_presenter = new Presenter(this, usercontrol1);
}
...
}
Basic idea is that view does not do cross talk. If user control needs to inform page some thing, it would raise an event that is caught by presenter and it informs page about it. Views are passive and handles UI.
Approach 2:
Usercontrol and Page interacts. In such case, Page will act as a ultimate view and Presenter will hold reference to it. Control's events will be handled by page and page will bubble up the event if necessary. For example,
IView1 : IView2 { }
public class Presenter1
{
IView1 _view1;
public Presenter1(IView1 view1)
{
_view1 = view1;
_view1.OnSave += OnSave;
_view1.OnSomeEvent += OnSomeEvent;
_view1.OnFoo += OnFoo;
}
...
}
public partial class MyPage : Page, IView1
{
public void Page_Load(...)
{
//do wire up
_presenter = new Presenter(this);
// handle user control events
UserControl1.Foo += UserControl1_OnFoo();
UserControl1.XyzEvent += UserControl1_XyzEvent();
}
...
private void UserControl1_OnFoo(...)
{
// bubble up to presenter
OnFoo(..)
}
private void UserControl1_XyzEvent(...)
{
// private interaction (purely about some UI manipulation),
// will not be bubble up to presenter
...
}
}

Having trouble deciding how to wire up a UserControl with MVVM

I've been doing the best I can to try to stay true to the separation recommended by the MVVM pattern. One thing I haven't figure out how to do correctly has to do with initializing my UserControls.
My most recent example of this has to do with a library that I wrote to talk to some low-level hardware. That assembly happens to have a UserControl that I can simply drop into any GUI that uses this hardware. All that is necessary for it to work is to set a reference to the object that has access to the low level methods.
However, that's where my problem lies -- currently, the UserControl is added to the GUI via XAML, where I define the namespace and then add the UserControl to my window. Of course, I have no control over its creation at this point, so the default constructor gets called. The only way to set the necessary reference for hardware control involves calling a method in the UC to do so. The ViewModel could feasibly call a method in the Model, e.g. GetController(), and then call the method in the UserControl to set the reference accordingly. The GUI can pass a reference to the UserControl to the ViewModel when said GUI creates the ViewModel, but this violates MVVM because the ViewModel shouldn't know anything about this control.
Another way I could deal with this is to not create the UserControl in XAML, but instead do it all from code-behind. After the ViewModel gets initialized and retrieves an initialized UserControl (i.e. one that has the low-level object reference set), it can set the Content of my Window to the UserControl. However, this also violates MVVM -- is there a way to databind the Content of a Window, TabControl, or any other element to a UserControl?
I'd like to hear if anyone has had to deal with this before, and if they approached it the first or second way I have outlined here, or if they took a completely different approach. If what I have asked here is unclear, please let me know and I'll do my best to update it with more information, diagrams, etc.
UPDATE
Thanks for the responses, guys, but I must not have explained the problem very well. I already use RelayCommands within the UserControl's ViewModel to handle all of the calls to the hardware layer (Model) when the user clicks in the control in the UserControl itself. My problem is related to initially passing a reference to the UserControl so it can talk to the hardware layer.
If I create the UserControl directly in XAML, then I can't pass it this reference via a constructor because I can only use the default constructor. The solution I have in place right now does not look MVVM-compliant -- I had to name the UserControl in XAML, and then in the code-behind (i.e. for the View), I have to call a method that I had added to be able to set this reference. For example, I have a GUI UserControl that contains the diagnostics UserControl for my hardware:
partial class GUI : UserControl
{
private MainViewModel ViewModel { get; set; }
public GUI( Model.MainModel model)
{
InitializeComponent();
ViewModel = new MainViewModel( model, this.Dispatcher);
ViewModel.Initialize();
this.DataContext = ViewModel;
diagnostics_toolbar.SetViewModel( ViewModel);
user_control_in_xaml.SetHardwareConnection( model.Connection);
}
}
where the outer class is the main GUI UserControl, and user_control_in_xaml is the UserControl I had to name in the GUI's XAML.
Looking at this again, I realize that it's probably okay to go with the naming approach because it's all used within the View itself. I'm not sure about passing the model information to user_control_in_xaml, because this means that a designer would have to know to call this method if he is to redo the GUI -- I thought the idea was to hide model details from the View layer, but I'm not sure how else to do this.
You will also notice that the main GUI is passed the Model in the constructor, which I assume is equally bad. Perhaps I need to revisit the design to see if it's possible to have the ViewModel create the Model, which is what I usually do, but in this case I can't remember why I had to create it outside of the GUI.
Am new to MVVM myself but here's a possible solution:
Create a property in your VM that is of the object type (that controls the hardware) and bind it to an attached property on your UserControl. Then you could set the property in your VM using dependency injection, so it would be set when the VM is created. The way I see it, the class that talks to the hardware (hardware controller) is a service. The service can be injected to your view model and bound to your UserControl. Am not sure if this is the best way to do it and if it is strict enough to all the MVVM principles but it seems like a possible solution.
if your question is: How do i show my viewmodel in the view? then my solution is always using viewmodelfirst approach and datatemplates.
so all you have to do is wire up your viewmodel via binding to a contentcontrol.content in xaml. wpf + datatemplates will do the work and instantiate your usercontrol for your viewmodel.
You are right, the ViewModel shouldn't know about anything in the View - or even that there is such a thing as a View, hence why MVVM rocks for unit testing too as the VM couldn't care less if it is exposing itself to a View or a test framework.
As far as I can see you might have to refactor things a little if you can. To stick to the MVVM pattern you could expose an ICommand, the ICommand calls an internal VM method that goes and gets the data (or whatever) from the Model, this method then updates an ObservableCollection property of the data objects for the View to bind to. So for example, in your VM you could have
private ICommand _getDataCommand;
public ICommand GetDataCommand
{
get
{
if (this._getDataCommand == null)
{
this._getDataCommand = new RelayCommand(param => this.GetMyData(), param => true);
}
return this._getDataCommand;
}
}
private void GetMyData{
//go and get data from Model and add to the MyControls collection
}
private ObservableCollection<MyUserControls> _uc;
public ObservableCollection<MyUserControls> MyControls
{
get
{
if (this._uc == null)
{
this._uc = new ObservableCollection<MyUserControls>();
}
return this._uc;
}
}
For the RelayCommand check out Josh Smiths MSDN article.
In the View you could either call the ICommand in the static constructor of your UC - I am guessing youwould need to add an event in your class for this - or call the ICommand from some sort of click event on your UC - maybe just have a 'load' button on the WPF window. And set the databinding of your UC to be the exposed observable collection of the VM.
If you can't change your UC at all then you could derive a new class from it and override certain behaviour.
Hope that helps a bit at least, like I say, have a look at Josh Smiths MVVM article as he covers the binding and ICommand stuff in there brilliantly.
If you set the DataContext of the Window or UserControl containing thisUserControl to the main view model, the user control can call SetHardwareConnection() on itself in its Loaded event (or DataContextChanged event handler).
If that's not possible because you're saying the UserControl is 'fixed', you should derive from it or wrap it up in another UserControl, which would serve as a MVVM 'adapter'.
(In order to bind the window: you could make the MainViewModel a singleton with a static Instance property and use DataContext="{x:Static MyClass.Instance}". A nice way to get things going quickly)
Note; this is based on my understanding that MVVM works because of Bindings.. I always bind the control to a ViewModel, not pass a ViewModel as a parameter.
Hope that helps!

Categories

Resources