Setting Caliburn.Micro ControlContent from another ViewModel - c#

I'm new to Caliburn.Micro (and MVVM for that matter) and I'm trying to Activate a screen with my conductor located in ShellViewModel from a button within a sub-viewmodel (one called by the conductor). All the tutorials I've seen have buttons in the actual shell that toggle between so I'm a little lost.
All the ViewModels share the namespace SafetyTraining.ViewModels
The ShellViewModel (first time ever using a shell so I might be using it in the wrong manner)
public class ShellViewModel : Conductor<object>.Collection.OneActive, IHaveDisplayName
{
public ShellViewModel()
{
ShowMainView();
}
public void ShowMainView()
{
ActivateItem(new MainViewModel());
}
}
ShellView XAML
<UserControl x:Class="SafetyTraining.Views.ShellView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<DockPanel>
<ContentControl x:Name="ActiveItem" />
</DockPanel>
MainViewModel - the main screen (does correctly display).
public class MainViewModel : Screen
{
public void ShowLoginPrompt()
{
LoginPromptViewModel lg = new LoginPromptViewModel();//This does happen
}
}
MainView XAML
<Button cal:Message.Attach="[Event Click] = [ShowLoginPrompt]">Login</Button>
LoginPromptViewModel
public class LoginPromptViewModel : Screen
{
protected override void OnActivate()
{
base.OnActivate();
MessageBox.Show("Hi");//This is for testing - currently doesn't display
}
}
EDIT Working Code:
Modified Sniffer's code a bit to properly fit my structure. Thanks :)
var parentConductor = (Conductor<object>.Collection.OneActive)(this.Parent);
parentConductor.ActivateItem(new LoginPromptViewModel());

You are doing everything correctly, but you are missing one thing though:
public void ShowLoginPrompt()
{
LoginPromptViewModel lg = new LoginPromptViewModel();//This does happen
}
You are creating an instance of LoginPromptViewModel, but you are not telling the conductor to activate this instance, so it's OnActivate() method is never called.
Now before I give you a solution I should suggest a couple of things:
If you are using the MainViewModel to navigate between different view-models then it would be appropriate to make MainViewModel a conductor itself.
If you aren't using it like that, then perhaps you should put the button that navigates to the LoginPromptViewModel in the ShellView itself.
Now back to your problem, since your MainViewModel extends Screen then it has a Parent property which refers to the Conductor, so you can do it like this:
public void ShowLoginPrompt()
{
LoginPromptViewModel lg = new LoginPromptViewModel();//This does happen
var parentConductor = (Conductor)(lg.Parent);
parentConductor.Activate(lg);
}

Related

How to change UserControl in background?

I am stuck with a problem where I want to change user control on different events in background. I am new in MVVM but I am bound to use MVVM only to achive this task. Code structure is little complex to me but still I figured that New Employee form is getting shown on button click but in new window but I want that form to be opened in current window's content. Code is given here which I need to modify to open usercontrol.
public Task<bool?> InitModification(CoreViewModel vm)
{
var tcs = new TaskCompletionSource<bool?>();
_dispatcherService.CurrentDispatcher.BeginInvoke(new Action(() =>
{
bool? result = null;
Window activeWindow = null;
for (var i = 0; i < Application.Current.Windows.Count; i++)
{
var win = Application.Current.Windows[i];
if ((win != null) && (win.IsActive))
{
activeWindow = win;
break;
}
}
if (activeWindow != null)
{
var win = new NewEmp(vm) { Owner = activeWindow };
result = win.ShowDialog();
}
tcs.SetResult(result);
}));
return tcs.Task;
}
My answer will not use your code since I don't find it useful to what you want to achieve. My answer will suffice with a suggestion on how you can achieve changing content control with MVVM
The way I go about it is with every MVVM-project I have a "application-shell" that acts as a wrapper for all my other content and through that you can easily change content. This application is a View and a ViewModel like such.
ShellView
<xmlns:ViewModel="clr-namespace:WhereOurViewModelIs.ViewModel">
<!--More XAML code-->
<Window.Resources>
<DataTemplate DataType="{x:Type ViewModel:MyViewModel}">
<Views:MyView/>
</DataTemplate>
<DataTemplate DataType="{x:Type ViewModel:AnotherViewModel}">
<Views:AnotherView/>
</DataTemplate>
</Window.Resources>
<ContentControl Content="{Binding CurrentPage}"/>
ShellViewModel
public class ShellViewModel
{
private BaseViewModel _currentPage{get;set;}
Public BaseViewModel CurrentPage{
get{return _currentPage;}
set{_currentPage = value; OnPropertyChanged();}
}
public ShellViewModel
{
CurrentPage = new MyViewModel();
}
}
Since we don't know how many different pages there is (in theory) we will tell them that need to be a of a type (inherited or an object) of BaseViewModel. This way we don't need to check for every single page and remove redundant code.
Then you set the Datacontext = new ShellViewModel(); in behind code of ShellView.xaml
BaseViewModel
public class BaseViewModel
{
/*This class can contains whatever you want your other ViewModels to be able to do*/
}
Now you need to set up 2 ViewModels with 2 Views just like we did with our shell.
MyViewModel
public class MyViewModel:BaseViewModel
{
/*Contains Properties,methods,private fields. What you want to show on view*/
}
AnotherViewModel
public class AnotherViewModel:BaseViewModel
{
/*Contains Properties,methods,private fields. What you want to show on view*/
}
Now you can set event to your ShellViewModel to change content whenever something happens. Hopefully this can atleast give you some idea how to work with MVVM. Of course you need to set up our ViewModels with properties changed event and other to get everything working, but this is a start for you.
If you find this answer helpful please chose it as an answer since it take some time to make an example like this.

View does not update with changing viewModel

I have a userControl named SensorControl which I want to bind its dataContext to a viewModel class named SensorModel.
The binding is successful and the initial values of viewModel is visible in the userControl, but the problem is that when I change the viewModel's properties, the userControl does not update, and I have to manually update that (by assigning null to its dataContext and assigning the viewModel again).
Here is a simplified example of my code.
SensorControl.xml:
<UserControl ...[other attributes]... DataContext={Binding Model}>
.
.
.
<Label Content="{Binding Title}"/>
.
.
.
</UserControl>
SensorControl.xml.cs (code-behind):
public partial class SensorControl : UserControl
{
public SensorModel model;
public SensorModel Model
{
get { return model; }
set { model = value; }
}
public SensorControl(SensorModel sm)
{
Model = sm;
}
}
MainWindow.xml.cs:
public partial class MainWindow : Window
{
public SensorModel sensorModel_1;
public SensorControl sensorControl_1;
public MainWindow()
{
InitializeComponent();
sensorModel_1 = new SensorModel(...[some arguments]...);
sensorControl_1 = new SensorControl(sensorModel_1);
mainGrid.Children.Add(sensorControl_1);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
sensorModel_1.Title = "myTitle";
//The UserControl does not update
}
0) I implemented INotifyPropertyChanged in SensorModel
1) The reason I need this, is that there is only one single concept of 'Sensor' in my project (it is a real electronic sensor) and therefore I have a single model for it (that deal with the real sensor, the database, etc), but in the UI I have multiple userControls for presenting different aspects of Sensor. So I have to create one instance of model (SensorModel) for each real sensor, and multiple userControls must bind to that (each one uses different parts of model).
2) I'm not that new to WPF, but I'm kind of new to MVVM and it's possible that I misunderstand something essential, so I would appreciate if someone could clearly explain the correct approach.
Thanks in advance
In your UserControl, remove the DataContext attribute and add an x:Name attribute. Then in your Label, bind like this:
<UserControl x:Name="uc">
<Label Content="{Binding ElementName=uc,Path=Model.Title}" />
</UserControl>
I believe the issue is the DataContext can't be set to Model because binding works off the parent's DataContext which will be based on mainGrid when it gets added as a child to that. Since the property "Model" doesn't exist in maiGrid's DataContext no binding will occur so your update won't reflect. Getting the DataContext of a UserControl properly can be tricky. I use the ElementName quite a bit or create DependencyProperties on the UserControl and then set them from the parent who will be using the control.
You need to set the DataContext to your ViewModel class in your View, and if you're applying the MVVM pattern, you should use ICommand for actions. Maybe it would be better If you'd implement a MainView class that does the logic in the background instead in the MainWindow class.
public MainWindow()
{
InitializeComponent();
DataContext = new MainView();
// sensorModel_1 = new SensorModel(...[some arguments]...);
// sensorControl_1 = new SensorControl(sensorModel_1);
// mainGrid.Children.Add(sensorControl_1);
}
Your MainView class :
public class MainView {
public SensorControl Control {get; internal set;}
...
}
And in your xaml change the binding :
<Label Content="{Binding Control.Model.Title}"/>
Thanks to all of you guys, I took your advices and finally I found a way.
1) I implemented an event in the SensorModel that fires every time any of properties changes (name ModelChanged)
2) Then as Merve & manOvision both suggested, I declared a dependency property in the SensorControl (of type SensorModel) and bind ui elements to that (Binding Path=Model.Title)
3) Then I used the ModelChanged event of this dependency property in the SensorControl and raise an event (of type INotifyPropertyChanged) so the bindings update their value
It works fine.

Can't complete pattern mediator in MVVM

i'm having a problem with mediator pattern in mvvm
I'l describe almost all classes for better understanding of my problem.
I'v got MainWindow and ViewModel for it, it is very simple and auctually doing nothing but holding one of my UserControls, there is a UserControl property in ViewModel that is binded to ContentControl.Content in MainWindow.
UserControls are identical there is only a single button in each of them,
and allso there are two ViewModels with commands to handle clikcs.
Class Mediator is a singletone and i tried to use it for iteraction between my ViewModel
So what i'm trying to do is to switch between UserControls, not creating them and their ViewModel inside a MainWindowViewModel. Switching must take place after i'm clicking a buttons. For example if i click on the button on FirstUserControl then ContentControl of the MainWindow should switch to SecondUserControl.
The probleam appears in UserControlsViewModels where i should pass UserControls object as a parameters in Mediator NotifyCollegue() function, but i have no acces to them
(of course, that is one of the principles of MVVM), and that is the problem of user types, because with standart types that should not be a problem (for example to pass int or string...).
i found this solutin here
http://www.codeproject.com/Articles/35277/MVVM-Mediator-Pattern
And why i can't swith UserControls in MainWindowViewModel, because i want the MainWindow to be clear of everything except current UserControl binded to ContentControl.
What may be possible solutions to this problem, should i make another singletone class and collect all the userControls references there and use them inside UserControlsViewModels, or maybe something else?
I hope that I have clearly described my problem, and that there is some kind of solution.
I will be glad to answer any question and very grateful for the help!!!
oh, and that is not the real app, i just want to get the idea(concept) of mesaging system between ViewModels, not mixing ViewModel and not creation Views and their ViewModels inside of other ViewModels...
Thanks again!
MainView
<Window x:Class="TESTPROJECT.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:TESTPROJECT"
mc:Ignorable="d"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
Title="MainWindow" Height="500" Width="750">
<Grid>
<ContentControl Grid.Row="1" Content="{Binding PagesControl}"/>
</Grid>
MainView ViewModel
namespace TESTPROJECT
{
class MainWindowViewModel : ViewModelBase
{
private UserControl _pagesControl;
public UserControl PagesControl
{
//Property that switches UserControls
set
{
_pagesControl = value;
OnPropertyChanged();
}
get
{
return _pagesControl;
}
}
public MainWindowViewModel()
{
//Method that will be listening all the changes from UserControls ViewModels
Mediator.Instance.Register(
(object obj) =>
{
PagesControl = obj as UserControl;
}, ViewModelMessages.UserWroteSomething);
}
}
}
FirstUserControl
<UserControl x:Class="TESTPROJECT.FirstUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:TESTPROJECT"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<Button Command="{Binding GetCommand}">
hello, i'm first user control!
</Button>
</Grid>
FirstUserControl ViewModel
namespace TESTPROJECT
{
class FirstUserControlViewModel : ViewModelBase
{
//command that is binded to button
private DelegateCommand getCommand;
public ICommand GetCommand
{
get
{
if (getCommand == null)
getCommand = new DelegateCommand(param => this.func(param), null);
return getCommand;
}
}
//method that will handle button click, and in it i'm sending a message
//to MainWindowViewModel throug Mediator class
//and that is allso a problem place because in theory i should
//pass the opposite UserControl object , but from here i have no
//acces to it
private void func(object obj)
{
Mediator.Instance.NotifyColleagues(
ViewModelMessages.UserWroteSomething,
"PROBLEM PLACE");
}
}
}
SecondUserControl
<UserControl x:Class="TESTPROJECT.SecondUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:TESTPROJECT"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<Button Command="{Binding GetCommand}">
Hello, i'm second user control!
</Button>
</Grid>
SecondUserControl ViewModel
namespace TESTPROJECT
{
class SecondUserControlViewModel : ViewModelBase
{
//command that is binded to button
private DelegateCommand getCommand;
public ICommand GetCommand
{
get
{
if (getCommand == null)
getCommand = new DelegateCommand(param => this.func(param), null);
return getCommand;
}
}
//method that will handle button click, and in it i'm sending a message
//to MainWindowViewModel throug Mediator class
//and that is allso a problem place because in theory i should
//pass the opposite UserControl object , but from here i have no
//acces to it
private void func(object obj)
{
Mediator.Instance.NotifyColleagues(
ViewModelMessages.UserWroteSomething,
"PROBLEM PLACE");
}
}
}
Class Mediator
and
enum ViewModelMessages
namespace TESTPROJECT
{
//this enum holding some kind of event names fro example UserWroteSomething
// is a name of switching one UserControl to another
public enum ViewModelMessages { UserWroteSomething = 1 };
class Mediator
{
//Singletone part
private static Mediator instance;
public static Mediator Instance
{
get
{
if (instance == null)
instance = new Mediator();
return instance;
}
}
private Mediator() { }
//Singletone part
//collection listeners that holds event names and handler functions
List<KeyValuePair<ViewModelMessages, Action<Object>>> internalList =
new List<KeyValuePair<ViewModelMessages, Action<Object>>>();
//new listener registration
public void Register(Action<object> callBack, ViewModelMessages message)
{
internalList.Add(
new KeyValuePair<ViewModelMessages, Action<Object>>(message, callBack));
}
// notifying all the listener about some changes
// and those whose names fits will react
public void NotifyColleagues(ViewModelMessages message, object args)
{
foreach(KeyValuePair<ViewModelMessages, Action<Object>> KwP in internalList)
if(KwP.Key == message)
KwP.Value(args);
}
}
}
App starting point
public partial class App : Application
{
private void Application_Startup(object sender, StartupEventArgs e)
{
FirstUserControl first = new FirstUserControl() { DataContext = new FirstUserControlViewModel() };
SecondUserControl second = new SecondUserControl() { DataContext = new SecondUserControlViewModel() };
new MainWindow()
{
DataContext = new MainWindowViewModel() { PagesControl = first }
}.ShowDialog();
}
}
If I understand you correctly, you want to navigate to another view (or view model respectively) when a certain action on the currently active view model happens (e.g. you press a button).
If you want to use your mediator for this, you could structure it like this:
public class Mediator
{
// These fields should be set via Constructor Injection
private readonly MainWindowViewModel mainWindowViewModel;
private readonly Dictionary<ViewModelId, IViewFactory> viewFactories;
public void NotifyColleagues(ViewModelId targetViewModelId, ViewModelArguments arguments)
{
var targetFactory = this.viewModelFactories[targetViewModelId];
var view = targetFactory.Create(viewModelArguments);
this.mainWindowViewModel.PagesControl = view;
}
// other members omitted to keep the example small
}
You would then create a factory for every view - view model combination. With the ViewModelArguments, you can pass information into the newly created view models that originate from other view models. ViewModelId can be a simple enum like your ViewModelMessage, instead you can also use the Type of the view model (which I would advise you to pursue).
Furthermore, I would advise you to not use a private constructor on the Mediator class because otherwise you cannot pass in the mainWindowViewModel and the dictionary for the view factories. You should be able to configure this in your Application-Startup method.
Also, please note that there are many other ways to structure MVVM applications, like e.g. using Data Templates to instantiate the view for a view model - but I think that is a bit too stretched for your little example.

Sharing data between different ViewModels

I'm trying to develop an easy MVVM project that it has two windows:
The first window is a text editor, where I bind some properties such as FontSize or BackgroundColor:
<TextBlock FontSize="{Binding EditorFontSize}"></TextBlock>
its DataContext is MainWindowViewModel:
public class MainWindowViewModel : BindableBase
{
public int EditorFontSize
{
get { return _editorFontSize; }
set { SetProperty(ref _editorFontSize, value); }
}
.....
The second window is the option window, where I have an slider for changing the font size:
<Slider Maximum="30" Minimum="10" Value="{Binding EditorFontSize }" ></Slider>
its DataContext is OptionViewModel:
public class OptionViewModel: BindableBase
{
public int EditorFontSize
{
get { return _editorFontSize; }
set { SetProperty(ref _editorFontSize, value); }
}
.....
My problem is that I have to get the value of the slider in the option window and then I have to modify the FontSize property of my TextBlock with this value. But I don't know how to send the font size from OptionViewModel to MainViewModel.
I think that I should use:
A shared model
A model in MainWindowViewModel and a ref of this model in OptionViewModel
Other systems like notifications, messages ...
I hope that you can help me. It's my first MVVM project and English isn't my main language :S
Thanks
Another option is to store such "shared" variables in a SessionContext-class of some kind:
public interface ISessionContext: INotifyPropertyChanged
{
int EditorFontSize { get;set; }
}
Then, inject this into your viewmodels (you are using Dependency Injection, right?) and register to the PropertyChanged event:
public class MainWindowViewModel
{
public MainWindowViewModel(ISessionContext sessionContext)
{
sessionContext.PropertyChanged += OnSessionContextPropertyChanged;
}
private void OnSessionContextPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "EditorFontSize")
{
this.EditorFontSize = sessionContext.EditorFontSize;
}
}
}
There are many ways to communicate between view models and a lot of points what the point is the best. You can see how it is done:
using MVVMLight
in Prism
by Caliburn
In my view, the best approach is using EventAggregator pattern of Prism framework. The Prism simplifies MVVM pattern. However, if you have not used Prism, you can use Rachel Lim's tutorial - simplified version of EventAggregator pattern by Rachel Lim.. I highly recommend you Rachel Lim's approach.
If you use Rachel Lim's tutorial, then you should create a common class:
public static class EventSystem
{...Here Publish and Subscribe methods to event...}
And publish an event into your OptionViewModel:
eventAggregator.GetEvent<ChangeStockEvent>().Publish(
new TickerSymbolSelectedMessage{ StockSymbol = “STOCK0” });
then you subscribe in constructor of another your MainViewModel to an event:
eventAggregator.GetEvent<ChangeStockEvent>().Subscribe(ShowNews);
public void ShowNews(TickerSymbolSelectedMessage msg)
{
// Handle Event
}
The Rachel Lim's simplified approach is the best approach that I've ever seen. However, if you want to create a big application, then you should read this article by Magnus Montin and at CSharpcorner with an example.
Update: For versions of Prism later than 5 CompositePresentationEvent is depreciated and completely removed in version 6, so you will need to change it to PubSubEvent everything else can stay the same.
I have done a big MVVM application with WPF. I have a lot of windows and I had the same problem. My solution maybe isn't very elegant, but it works perfectly.
First solution: I have done one unique ViewModel, splitting it in various file using a partial class.
All these files start with:
namespace MyVMNameSpace
{
public partial class MainWindowViewModel : DevExpress.Mvvm.ViewModelBase
{
...
}
}
I'm using DevExpress, but, looking your code you have to try:
namespace MyVMNameSpace
{
public partial class MainWindowViewModel : BindableBase
{
...
}
}
Second solution: Anyway, I have also a couple of different ViewModel to manage some of these windows. In this case, if I have some variables to read from one ViewModel to another, I set these variables as static.
Example:
public static event EventHandler ListCOMChanged;
private static List<string> p_ListCOM;
public static List<string> ListCOM
{
get { return p_ListCOM; }
set
{
p_ListCOM = value;
if (ListCOMChanged != null)
ListCOMChanged(null, EventArgs.Empty);
}
}
Maybe the second solution is simplier and still ok for your need.
I hope this is clear. Ask me more details, if you want.
I'm not a MVVM pro myself, but what I've worked around with problems like this is,
having a main class that has all other view models as properties, and setting this class as data context of all the windows, I don't know if its good or bad but for your case it seems enough.
For a more sophisticated solution see this
For the simpler one,
You can do something like this,
public class MainViewModel : BindableBase
{
FirstViewModel firstViewModel;
public FirstViewModel FirstViewModel
{
get
{
return firstViewModel;
}
set
{
firstViewModel = value;
}
}
public SecondViewModel SecondViewModel
{
get
{
return secondViewModel;
}
set
{
secondViewModel = value;
}
}
SecondViewModel secondViewModel;
public MainViewModel()
{
firstViewModel = new FirstViewModel();
secondViewModel = new SecondViewModel();
}
}
now you have to make another constructor for your OptionWindow passing a view model.
public SecondWindow(BindableBase viewModel)
{
InitializeComponent();
this.DataContext = viewModel;
}
this is to make sure that both windows work on the same instance of a view model.
Now, just wherever you're opening the second window use these two lines
var window = new SecondWindow((ViewModelBase)this.DataContext);
window.Show();
now you're passing the First Window's view model to the Second window, so that they work on the same instance of the MainViewModel.
Everything is done, just you've to address to binding as
<TextBlock FontSize="{Binding FirstViewModel.EditorFontSize}"></TextBlock>
<TextBlock FontSize="{Binding SecondViewModel.EditorFontSize}"></TextBlock>
and no need to say that the data context of First window is MainViewModel
In MVVM, models are the shared data store. I would persist the font size in the OptionsModel, which implements INotifyPropertyChanged. Any viewmodel interested in font size subscribes to PropertyChanged.
class OptionsModel : BindableBase
{
public int FontSize {get; set;} // Assuming that BindableBase makes this setter invokes NotifyPropertyChanged
}
In the ViewModels that need to be updated when FontSize changes:
internal void Initialize(OptionsModel model)
{
this.model = model;
model.PropertyChanged += ModelPropertyChanged;
// Initialize properties with data from the model
}
private void ModelPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(OptionsModel.FontSize))
{
// Update properties with data from the model
}
}
I'm new to WPF and I've come up with a solution to this and I'm curious of more knowledgeable people's thoughts about what's right and wrong with it.
I have an Exams tab and a Templates tab. In my simple proof of concept, I want each tab to "own" an Exam object, and to be able to access the other tab's Exam.
I define the ViewModel for each tab as static because if it's a normal instance property, I don't know how one tab would get the actual instance of the other tab. It feels wrong to me, though it's working.
namespace Gui.Tabs.ExamsTab {
public class GuiExam: INotifyPropertyChanged {
private string _name = "Default exam name";
public string Name {
get => _name;
set {
_name = value;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName="") {
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public partial class ExamsHome : Page {
public ExamsHome() {
InitializeComponent();
DataContext = ViewModel;
}
public static readonly ExamsTabViewModel ViewModel = new ExamsTabViewModel();
}
public class ExamsTabViewModel {
public GuiExam ExamsTabExam { get; set; } = new GuiExam() { Name = "Exam from Exams Tab" };
public GuiExam FromTemplatesTab { get => TemplatesHome.ViewModel.TemplatesTabExam; }
}
}
namespace Gui.Tabs.TemplatesTab {
public partial class TemplatesHome : Page {
public TemplatesHome() {
InitializeComponent();
DataContext = ViewModel;
}
public static readonly TemplatesTabViewModel ViewModel = new TemplatesTabViewModel();
}
public class TemplatesTabViewModel {
public GuiExam TemplatesTabExam { get; set; } = new GuiExam() { Name = "Exam from Templates Tab" };
public GuiExam FromExamTab { get => ExamsHome.ViewModel.ExamsTabExam; }
}
}
And then everything is accessible in the xaml:
TemplatesHome.xaml (excerpt)
<StackPanel Grid.Row="0">
<Label Content="From Exams Tab:"/>
<Label FontWeight="Bold" Content="{Binding FromExamTab.Name}"/>
</StackPanel>
<StackPanel Grid.Row="1">
<Label Content="Local Content:"/>
<TextBox Text="{Binding TemplatesTabExam.Name, UpdateSourceTrigger=PropertyChanged}"
HorizontalAlignment="Center" Width="200" FontSize="16"/>
</StackPanel>
ExamsHome.xaml (excerpt)
<StackPanel Grid.Row="0">
<Label Content="Local Content:"/>
<TextBox Text="{Binding ExamsTabExam.Name, UpdateSourceTrigger=PropertyChanged}"
HorizontalAlignment="Center" Width="200" FontSize="16"/>
</StackPanel>
<StackPanel Grid.Row="1">
<Label Content="From Templates Tab:"/>
<Label FontWeight="Bold" Content="{Binding FromTemplatesTab.Name}"/>
</StackPanel>

Correct approach to UserControl creation when using MVVM

This is more of a conceptual question rather than a practical one. I'm just starting to learn the MVVM concept for developing UI , and I've come across a dillema I'm not sure the answer to:
Say I have a main window and a little pop-up window (meaning it's a small window with some UI elements in it). The structure of the program will look something like this:
MainWindow
model <-- MainWindowViewModel.cs <-- MainWindowView.xaml (containing no code-behind)
PopUpWindow (A UserControl)
model <-- PopUpWindowViewModel.cs <-- PopUpWindowView.xaml (containing no code-behind)
*the model is just a bunch of BL classes that are irrelevant for this question.
Now , lets say I want to create a new PopUp window from inside the MainWindowViewModel (or even save an instance of it in a private data-member). What is the correct way of doing so?
The way I see it I can't do something like this :
PopUpWindow pop = new PopUpWindow()
Because it kind of defeats the purpose of abstracting the view from the view model(What if a year from now i'll want to create a better version of the PopUpWindow using the same PopUpWindowViewModel?).
On the other hand , I can't initialize a new instnace of the PopUpWindow using just it's view model (The viewModel as I understand is not supposed to know anything about the view that will use it).
Hope it all makes sense... so what would you do in that situation?
*Just to clarify it further , let's say for argument's sake that the situation I'm describing is a button on the MainWindowView that upon clicking will open a PopUpWindowView.
Thanks in advnace.
I had somewhat a similar dilemma and I'll explain how I solved it.
Let's say you have MainWindow and a SettingsWindow, which you want to display when the SettingsButton is clicked.
You have two respective view models, MainWindowViewModel and SettingsViewModel, which you will be passing as their Window.DataContext properties.
Your MainWindowViewModel should expose an ICommand property named SettingsButtonCommand (or similar). Bind this command to the SettingsButton.Command.
Now your command should invoke something like this:
void OnSettingsButtonClicked()
{
var viewModel = new SettingsViewModel();
var window = new SettingsWindow();
window.DataContext = viewModel;
window.Show();
}
There is a slight issue when you want to use Window.ShowDialog(), because you need to resume execution.
For these cases I have an asynchronous variant of the DelegateCommand:
public sealed class AsyncDelegateCommand : ICommand
{
readonly Func<object, Task> onExecute;
readonly Predicate<object> onCanExecute;
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public AsyncDelegateCommand(Func<object, Task> onExecute)
: this(onExecute, null) { }
public AsyncDelegateCommand(Func<object, Task> onExecute, Predicate<object> onCanExecute)
{
if (onExecute == null)
throw new ArgumentNullException("onExecute");
this.onExecute = onExecute;
this.onCanExecute = onCanExecute;
}
#region ICommand Methods
public async void Execute(object parameter)
{
await onExecute(parameter);
}
public bool CanExecute(object parameter)
{
return onCanExecute != null ? onCanExecute(parameter) : true;
}
#endregion
}
You've specifically said that the popup is a UserControl so you can use basic data templating. First create view models for your main window and popup control:
public class MainViewModel : ViewModelBase
{
private PopUpViewModel _PopUp;
public PopUpViewModel PopUp
{
get { return _PopUp; }
set { _PopUp = value; RaisePropertyChanged(() => this.PopUp); }
}
}
public class PopUpViewModel : ViewModelBase
{
private string _Message;
public string Message
{
get { return _Message; }
set { _Message = value; RaisePropertyChanged(() => this.Message); }
}
}
The MainViewModel's PopUp member is initially null, we'll set it to an instance of PopUpViewModel when we want the popup to appear. To do that we create a content control on the main window and set it's content to that member. We also use a data template to specify the type of child control to create when the popup view model has been set:
<Window.Resources>
<DataTemplate DataType="{x:Type local:PopUpViewModel}">
<local:PopUpWindow />
</DataTemplate>
</Window.Resources>
<StackPanel>
<Button Content="Show PopUp" Click="Button_Click_1" HorizontalAlignment="Left"/>
<ContentControl Content="{Binding PopUp}" />
</StackPanel>
I'm doing a big no-no here by creating the view model in the code-behind along with a click handler, but it's just for illustrative purposes:
public partial class MainWindow : Window
{
MainViewModel VM = new MainViewModel();
public MainWindow()
{
InitializeComponent();
this.DataContext = this.VM;
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
this.VM.PopUp = new PopUpViewModel { Message = "Hello World!" };
}
}
That's it! Click the button, popup window appears underneath it showing the content. Now it may not always be this simple, sometimes you may want to create multiple children on a parent control...in that case you'd set up an ItemsControl, set its panel to a Grid (say) and modify the data templates to set the Margin etc on each element to position them. Or you may not always know what type of view model is going to be created, in which case you need to add multiple data templates for each type you're expecting. Either way you still have good separation of concerns because it is the views that are deciding how to display the content in the view models. The view models themselves still don't know anything about the views and they can be unit-tested etc independently.

Categories

Resources