I'm very new to Caliburn Micro and would like to access ViewModel properties during OnExit.
public class AppBootstrapper : Bootstrapper<MainViewModel>
{
protected override void OnExit(object sender, EventArgs e)
{
if (mainViewModel.MyParam == 42)
{
}
base.OnExit(sender, e);
}
From the default WP7 template (without Caliburn) i'm used to have App.ViewModel, which is a static field with a singleton get accessor, where the viewmodel will be created on the first access.
(See next code snippet)
public partial class App : Application
{
private static MainViewModel viewModel = null;
public static MainViewModel ViewModel
{
get
{
// Delay creation of the view model until necessary
if (viewModel == null)
viewModel = new MainViewModel();
return viewModel;
}
set
{
viewModel = value;
}
}
Now i try to use Caliburn Micro 1.1 with a WPF project and don't know how this should be done.
I need access to the ViewModel during OnExit inside AppBootStrapper.
I assume, that this should be possible, because my AppBootstrapper is inherited from Bootstrapper, but can't find the right way of doing this..
Any hints, how this can be done in WPF are very welcome?
Thanks
Rob
Try
MainViewModel mainViewModel = IoC.Get<MainViewModel>();
Here is how it would look in your code:
public class AppBootstrapper : Bootstrapper<MainViewModel>
{
protected override void OnExit(object sender, EventArgs e)
{
// Get the Main View Model
MainViewModel mainViewModel = IoC.Get<MainViewModel>();
if (mainViewModel.MyParam == 42)
{
//Do work
}
base.OnExit(sender, e);
}
}
This assumes Two Things:
Your MainViewModel class is exporting typeof(MainViewModel) and not something different, like typeof(IShell)
You are using the default MEF implementation of C.M.
After searching a little bit more i think i've found the solution to my own question: Added SimpleContainer.cs from here: link
and added this to my AppBootstrapper code:
public class AppBootstrapper : Bootstrapper<MainViewModel>
{
private SimpleContainer container;
protected override void Configure()
{
container = new SimpleContainer();
container.RegisterSingleton(typeof(MainViewModel), null, typeof(MainViewModel));
container.RegisterSingleton(typeof(IWindowManager), null, typeof(WindowManager));
}
protected override object GetInstance(Type service, string key)
{
return container.GetInstance(service, key);
}
Would be great to hear some comment, whether this is ok or not.
Related
So I have one main Form that works as the navigation bar and two UserControls that display some controls.
In UserControlsA I have some fields that require to be filled. With that data I create an Object that contains some information. I require to pass that object to UserControlsB so I can display some data there.
My idea was to make three instances of the object, one in the UserControlsA to get the information required for the object, one in the main form to get a "copy" of the object from UserControlsA, and one in UserControlsB that can get the information from the main Form.
However, this seems redundant and doesn't even work. Here's some code:
Main Form:
public partial class main : Form
{
public Object object { get; set; }
public UCA uca;
public UCB ucb;
public Form1()
{
InitializeComponent();
uca = new UCA();
ucb = new UCB();
panel2.Controls.Add(uca);
panel2.Controls.Add(ucb);
ucb.Visible = false;
uca.Visible = true;
}
private void button1_Click(object sender, EventArgs e)
{
ucb.Visible = false;
uca.Visible = true;
}
private void button2_Click(object sender, EventArgs e)
{
ucb.Visible = true;
uca.Visible = false;
}
}
UserControlsA:
public partial class UCA : UserControl
{
public Object object { get; set; }
public UCA()
{
InitializeComponent();
}
private void bUsage_Click(object sender, EventArgs e)
{
//Data is provided
object = new Object(data);
//I use var parent to try and access the object from the main form.
var parent = Parent as Form1;
object = parent.object;
}
}
UsercontrolB:
public partial class UCB : UserControl
{
public Object object { get; set; }
public UCB()
{
InitializeComponent();
}
public void updateData()
{
//I try to assign the object from the main form to this form's object.
var parent = Parent as Form1;
object = parent.object;
}
}
Using var Parent doesn't work. What can I do?
A couple of examples using the INotifyPropertyChanged Interface and an implementation that makes use of standard public events.
Related Documentation:
Windows Forms Data Binding
Change Notification in Windows Forms Data Binding
Interfaces Related to Data Binding
Using INotifyPropertyChanged:
The UserControl exposes a public Property (here, named CustomDataObject, simple string Type in the first example, object in the second. It can another Type of course).
The Property is decorated with the Bindable attribute. The BindingDirection here is more a description of the intent, there's no Template attached to it.
Two other standard Attributes are added:
DefaultValue defines the default value of a Property (the value assigned to the Property when the Control is created). It's used by the Code Generator to determine whether the current value should be serialized: it's not serialized if it matches the value set by the Attribute.
It's also used by the PropertyGrid to show, in bold, a non-default value selection or assignment.
DesignerSerializationVisibility specifies the how the Property should be serialized at design-time. Here, is set to DesignerSerializationVisibility.Visible, to signify that the Property should be serialized.
The INotifyPropertyChanged Interface can be seen as a simplified way to add Property bindings to more than one property, using the same event handler, to notify a change in value.
The default implementation of the Interface simply requires that a a public Event of type PropertyChangedEventHandler is added to the class.
When a Property value is changed, the setter just invokes the Event. There are slightly different ways to perform this action; here I'm using a OnPropertyChanged() method that uses the CallerMemberName Attribute to acquire the name of the Property that calls it. It's fairly common in both WinForms and WPF.
UCA UserControl:
The UserControl (see the visual example), has two Buttons that change the bound CustomDataObject Property value. Their Click action is handled by ButtonsAction_Click.
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows.Forms;
public partial class UCA : UserControl, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string m_DataObject = string.Empty;
public UCA() => InitializeComponent();
[Bindable(true, BindingDirection.TwoWay), DefaultValue("")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public string CustomDataObject {
get => m_DataObject;
set {
if (m_DataObject != value){
m_DataObject = value;
OnPropertyChanged();
}
}
}
private void OnPropertyChanged([CallerMemberName] string propertyName = "") =>
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
private void ButtonsAction_Click(object sender, EventArgs e)
{
var btn = sender as Button;
CustomDataObject = (btn == SomeButton) ? txtInput1.Text : txtInput2.Text;
}
}
UCB UserControl:
This other UserControl is the receiver. It just exposes a public Property (ReceiverDataObject) that will be bound to the CustomDataObject Property of UCA.
The ReceiverDataObject property is also defined as [Bindable], with the intention of making it one-way only. The property doesn't raise any event. It receive a value, stores it in a private Field and sets an internal UI element.
public partial class UCB : UserControl
{
private string m_RecvDataObject = string.Empty;
public UCB() => InitializeComponent();
[Bindable(true, BindingDirection.OneWay)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public string ReceiverDataObject {
get => m_RecvDataObject;
set {
m_RecvDataObject = value;
txtPresenter.Text = m_RecvDataObject;
}
}
}
Using Standard Events notifications:
You can also generate Property change notifications using standard Events.
The difference is that you need an Event for each Property that should notify changes.
If you already have Event delegates used for this, then it's probably a good choice, since there's very few to add: just call the protected method that raises the Event in the Property setter.
Here, I'm, using the common .Net Event handling, using the EventHandlerList defined by the underlying Component class and exposed by its Events property, to add remove event subscriptions.
The Events are usually raised calling a protected method that has the same name of the Event, except the On prefix.
Here, CustomDataObjectChanged Event => OnCustomDataObjectChanged() method.
You can see this pattern in all standard Controls.
▶ The CustomDataObjectChanged name assigned to the Event is not a choice: this event must have the same name of the Property and the Changed suffix.
This is the pattern, it's enough to just follow it.
UCA UserControl:
public partial class UCA : UserControl
{
private static readonly object Event_CustomDataObjectChanged = new object();
private object m_DataObject = null;
public UCButtonActions() => InitializeComponent();
[Bindable(BindableSupport.Yes, BindingDirection.TwoWay), DefaultValue(null)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public object CustomDataObject {
get => m_DataObject;
set {
if (m_DataObject != value){
m_DataObject = value;
OnCustomDataObjectChanged(EventArgs.Empty);
}
}
}
public event EventHandler CustomDataObjectChanged {
add {
Events.AddHandler(Event_CustomDataObjectChanged, value);
}
remove {
Events.RemoveHandler(Event_CustomDataObjectChanged, value);
}
}
protected virtual void OnCustomDataObjectChanged(EventArgs e)
{
if (Events[Event_CustomDataObjectChanged] is EventHandler evth) evth(this, e);
}
}
UCB UserControl:
The second UserControl doesn't change. It's just the receiver.
The Form class (or another class used as Handler):
In the Form Constructor, or any other method called after the Form initialization, use the DataBindings property of UCB to link the Properties of the two UserControls:
public SomeForm()
{
InitializeComponent();
ucb1.DataBindings.Add("ReceiverDataObject", uca1, "CustomDataObject",
false, DataSourceUpdateMode.OnPropertyChanged);
}
You can also use a BindingSource to mediate:
BindingSource ucsSource = null;
public SomeForm()
{
InitializeComponent();
ucsSource = new BindingSource(uca1, null);
ucb1.DataBindings.Add("ReceiverDataObject", ucsSource, "CustomDataObject",
false, DataSourceUpdateMode.OnPropertyChanged);
}
Sample functionality:
Maybe you should redesign your data flow. UserControl should not usually make assumptions of what its parent would be, that's why it's a "customized control". It can be a Form1 but not necessary. So you shouldn't do casting like in your example.
To provide the information from A to B, one way is to create public Get/Set methods or properties for those controls. And the main form works with those public members, pseudo-code can be:
class main{
UCA uca;
UCB ucb;
public void RefreshData(){
object data = uca.GetData();
ucb.UpdateData(data);
}
}
So I just learned how to properly use events I guess. Here's how the code looks now:
Main form:
public partial class main : Form
{
public UCA uca;
public UCB ucb;
public delegate void passObject(object source, someObject u);
public Form1()
{
InitializeComponent();
uca = new UCA();
ucb = new UCB();
panel2.Controls.Add(uca);
panel2.Controls.Add(ucb);
ucb.Visible = false;
uca.Visible = true;
}
private void Form1_Load(object sender, EventArgs e)
{
uca.objectRequired += ucb.ucb_objectRequired;
}
private void button1_Click(object sender, EventArgs e)
{
ucb.Visible = false;
uca.Visible = true;
}
private void button2_Click(object sender, EventArgs e)
{
ucb.Visible = true;
uca.Visible = false;
}
}
Usercontrol A:
public partial class UCA : UserControl
{
public someObject o { get; set; }
public event passObject objectRequired;
public UCA()
{
InitializeComponent();
}
private void bUsage_Click(object sender, EventArgs e)
{
//Data is provided
o = new someObject(data);
usageRequired?.Invoke(this, o);
}
}
Usercontrol B:
public partial class UCB : UserControl
{
public SomeObject o { get; set; }
public UCDetails()
{
InitializeComponent();
}
public void ucn_objectRequired(object sender, sObject u)
{
o = u;
//Use the data from the object.
}
}
I am new to MvvmCross and still figuring out how things are done. I am using BEMCheckBox for one of my developing applications and I tried to bind BEMCheckBox's "On" property to ViewModel. Unfortunately, it is not working as expected.
BEMCheckBox
Github : https://github.com/saturdaymp/XPlugins.iOS.BEMCheckBox
NuGet : SaturdayMP.XPlugins.iOS.BEMCheckBox
Version: 1.4.3
MvvmCross
Version : 6.4.2
This is my View Class
[MvxFromStoryboard("Main")]
[MvxRootPresentation(WrapInNavigationController = false)]
public partial class MyView : BaseView<MyViewModel>
{
private BEMCheckBox CheckBox;
public MyView(IntPtr handle) : base(handle)
{
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
//add check box
CheckBox = new BEMCheckBox(new CoreGraphics.CGRect(0, 0, 20, 20))
{
BoxType = BEMBoxType.Square,
TintColor = UIColor.FromRGBA(0, 0, 0, 0.14f),
OnFillColor = UIColor.FromRGB(42, 183, 202),
OnCheckColor = UIColor.White,
OnTintColor = UIColor.FromRGBA(0, 0, 0, 0.14f),
OnAnimationType = BEMAnimationType.Bounce,
OffAnimationType = BEMAnimationType.Bounce,
On = false,
CornerRadius = 0,
};
//CheckBoxContainerView is an UIView
CheckBoxContainerView.AddSubview(CheckBox);
CheckBoxContainerView.BackgroundColor = UIColor.Clear;
//Binding to View Model
var set = this.CreateBindingSet<MyView, MyViewModel>();
set.Bind(CheckBox).For(c => c.On).To(vm => vm.IsCheckBoxOn);
set.Apply();
}
}
This is my ViewModel Class
public class MyViewModel : BaseViewModel
{
private bool _isCheckBoxOn;
public bool IsCheckBoxOn
{
get => _isCheckBoxOn;
set
{
SetProperty(ref _isCheckBoxOn, value);
Console.WriteLine(_isCheckBoxOn);
}
}
public MyViewModel : base()
{
}
public override Task Initialize()
{
return base.Initialize();
}
}
When I do the same thing for UISwitch it works perfectly. Any help would be highly appreciated.
MvvmCross includes many target bindings out of the box, UISwitch being one of them. For a complete list see "built-in-bindings" in MvvmCross documentation.
One-way binding (ViewModel -> View)
By default, you can create a binding to assign a value to a property on your view from your view model, this is called one-way binding. The approach works even with custom 3rd party controls, as long as the types match.
Two-way binding (ViewModel -> View && View -> ViewModel)
In order to do a two-way bind, MvvmCross needs a mechanise for the view to notify the view model that a value of the view has changed. For this MvvmCross using target bindings. See MvvCross documentation for creating custom target bindings.
Example
See MvvmCross source code for MvxUISwitchOnTargetBinding.cs which shows how they do the binding for the UISwitch control and the On state.
public class MvxUISwitchOnTargetBinding : MvxTargetBinding<UISwitch, bool>
{
private IDisposable _subscription;
public MvxUISwitchOnTargetBinding(UISwitch target)
: base(target)
{
}
protected override void SetValue(bool value)
{
Target.SetState(value, true);
}
public override void SubscribeToEvents()
{
var uiSwitch = Target;
if (uiSwitch == null)
{
MvxBindingLog.Error( "Error - Switch is null in MvxUISwitchOnTargetBinding");
return;
}
_subscription = uiSwitch.WeakSubscribe(nameof(uiSwitch.ValueChanged), HandleValueChanged);
}
public override MvxBindingMode DefaultMode => MvxBindingMode.TwoWay;
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
if (!isDisposing) return;
_subscription?.Dispose();
_subscription = null;
}
private void HandleValueChanged(object sender, EventArgs e)
{
FireValueChanged(Target.On);
}
}
Note the HandleValueChanged method which calls the FireValueChanged() method, this is the method that passes the value that you want to send back up to your bound view model.
You will then need to register your custom target bindings in your Setup.cs class by overriding the FillTargetFactories.
I didn't know how better to word the title so I went with solution that came to my mind.
Here is the problem. I have a page that has list and each item on the lists opens a detail page (on click). But the VM is reused, which causes me several problems.
Previous data can be seen for split second when opening a the detail page
I need certain properties to be set to specific values when the page open, but since the VM is reused it keeps all the values from the previous detail and this messes up my logic.
This UWP app. I'm using Template10 framework's NavigationService to move between pages.
Main Page ViewModel
public class MainPageViewModel : ViewModelBase {
private List<MangaItem> _mangaList;
public List<MangaItem> mangaList {
get { return _mangaList; }
set { Set(ref _mangaList, value); }
}
private string _mainSearchText;
public string mainSearchText {
get { return _mainSearchText; }
set { Set(ref _mainSearchText, value); }
}
public MainPageViewModel() {
_mangaList = new List<MangaItem>();
mangaList = new List<MangaItem>();
Initialize();
}
private async void Initialize() {
mangaList = await MangaListGet.GetListAsync();
}
public async void MainSearchSubmitted() {
mangaList = await MangaListGet.GetListAsync(_mainSearchText);
}
public void MangaSelected(object sender, ItemClickEventArgs e) {
var mangaItem = (MangaItem)e.ClickedItem;
NavigationService.Navigate(typeof(Views.MangaDetail), mangaItem.id);
}
}
And Detail Page ViewModel
class MangaDetailViewModel : ViewModelBase {
private MangaItem _mangaDetail;
public MangaItem mangaDetail {
get { return _mangaDetail; }
set { Set(ref _mangaDetail, value); }
}
private string _mangaId;
public override async Task OnNavigatedToAsync(object parameter, NavigationMode mode, IDictionary<string, object> suspensionState) {
_mangaId = parameter as string;
Initialize();
await Task.CompletedTask;
}
private async void Initialize() {
mangaDetail = await MangaDetailGet.GetAsync(_mangaId);
}
public void ChapterSelected(object sender, ItemClickEventArgs e) {
var _chapterId = (ChapterListItem)e.ClickedItem;
NavigationService.Navigate(typeof(Views.ChapterPage), _chapterId.id);
}
}
This code only shows the first problem is displaying previously loaded data for a split second. If needed I will add code that showcases the other problem, but I' not sure if it's really relevant right now. I'm thinking that maybe my entire logic is flawed or something.
EDIT:
<Page.DataContext>
<vm:ChapterPageViewModel x:Name="ViewModel" />
</Page.DataContext>
where vm is xmlns:vm="using:MangaReader.ViewModels".
Another solution is to use Bootstrapper.ResolveforPage() which is intended to handle dependency injection but would easily serve your needs. Like this:
[Bindable]
sealed partial class App : BootStrapper
{
static ViewModels.DetailPageViewModel _reusedDetailPageViewModel;
public override INavigable ResolveForPage(Page page, NavigationService navigationService)
{
if (page.GetType() == typeof(Views.DetailPage))
{
if (_reusedDetailPageViewModel == null)
{
_reusedDetailPageViewModel = new ViewModels.DetailPageViewModel();
}
return _reusedDetailPageViewModel;
}
else
{
return null;
}
}
}
The NavigationService will treat this the same as any other view-model. Meaning it will call OnNavTo() and the other navigation overrides you include.
Best of luck.
While Template10 documentation states the NavigationCacheMode is disabled by default, that isn't the case in it's example templates (as of writing this). This is set in View C# code (.xaml.cs file).
.xaml.cs file
namespace MangaReader.Views {
public sealed partial class MangaDetail : Page {
public MangaDetail() {
InitializeComponent();
//NavigationCacheMode = Windows.UI.Xaml.Navigation.NavigationCacheMode.Enabled; //this was set by default
NavigationCacheMode = Windows.UI.Xaml.Navigation.NavigationCacheMode.Disabled;
}
}
}
Now, new ViewModel will be created each time you access a this page.
I'm using NInject to resolve the dependency for my first WPF application.
Following are my code snippets.
My App.xaml.cs goes like.
public partial class App : Application
{
private IKernel container;
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
ConfigureContainer();
ComposeObjects();
}
private void ComposeObjects()
{
Current.MainWindow = this.container.Get<MainWindow>();
}
private void ConfigureContainer()
{
this.container = new StandardKernel();
container.Bind<ISystemEvents>().To<MySystemEvents>();
}
}
App.xaml goes like this.
<Application x:Class="Tracker.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Application.Resources>
</Application.Resources>
</Application>
MainWindow.xaml.
<Window x:Class="Tracker.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:viewmodel="clr-namespace:Tracker.ViewModel"
Title="MainWindow" Height="150" Width="350">
<Window.DataContext>
<viewmodel:TrackerViewModel>
</viewmodel:TrackerViewModel>
</Window.DataContext>
<Grid>
</Grid>
</Window>
MainWindow.xaml.cs
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
and viewmodel
internal class TrackerViewModel : System.ComponentModel.INotifyPropertyChanged
{
public TrackerViewModel(ISystemEvents systemEvents)
{
systemEvents.SessionSwitch += SystemEvents_SessionSwitch;
}
private void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
{
}
}
Now when I launch the application, I get an exception An unhandled exception of type 'System.NullReferenceException' occurred in PresentationFramework.dll in InitializeComponent() method.
I know its because of the viewmodel class not have parameterless constructor. But I am not able to undestand why dependency injector is not able to resolve this? Am I doing something wrong?
Any help would be greatly appreciated.
First of all, I recommend reading the book Dependency Injection in .NET, especially the section about WPF. But even if you don't read it, there is a helpful example in the code download for the book.
You have already worked out that you need to remove the StartupUri="MainWindow.xaml" from your App.xaml file.
However, when using DI you must not wire up the DataContext declaratively otherwise it will only be able to work with the default constructor.
<Window x:Class="WpfWithNinject.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="150" Width="350">
</Window>
The pattern that is used in WPF is a bit confusing when it comes to DI. The main issue is that if you want your ViewModel to be able to control its own windowing environment, there is a circular dependency issue between the MainWindow and its ViewModel, so you will need to make an Abstract Factory in order to instantiate the ViewModel so the dependencies can be satisfied.
Creating the ViewModel Factory
internal interface ITrackerViewModelFactory
{
TrackerViewModel Create(IWindow window);
}
internal class TrackerViewModelFactory : ITrackerViewModelFactory
{
private readonly ISystemEvents systemEvents;
public TrackerViewModelFactory(ISystemEvents systemEvents)
{
if (systemEvents == null)
{
throw new ArgumentNullException("systemEvents");
}
this.systemEvents = systemEvents;
}
public TrackerViewModel Create(IWindow window)
{
if (window == null)
{
throw new ArgumentNullException("window");
}
return new TrackerViewModel(this.systemEvents, window);
}
}
The TrackerViewModel also needs to have some rework so it can accept the IWindow into its constructor. This allows the TrackerViewModel to control its own windowing environment, such as showing modal dialog boxes to the user.
internal class TrackerViewModel : System.ComponentModel.INotifyPropertyChanged
{
private readonly IWindow window;
public TrackerViewModel(ISystemEvents systemEvents, IWindow window)
{
if (systemEvents == null)
{
throw new ArgumentNullException("systemEvents");
}
if (window == null)
{
throw new ArgumentNullException("window");
}
systemEvents.SessionSwitch += SystemEvents_SessionSwitch;
this.window = window;
}
private void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
{
}
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
}
Adapting the Window
You need to fix up the framework a bit with an abstract type for the windows, IWindow, and an abstraction to help manage DI of each of the windows, WindowAdapter.
internal interface IWindow
{
void Close();
IWindow CreateChild(object viewModel);
void Show();
bool? ShowDialog();
}
internal class WindowAdapter : IWindow
{
private readonly Window wpfWindow;
public WindowAdapter(Window wpfWindow)
{
if (wpfWindow == null)
{
throw new ArgumentNullException("window");
}
this.wpfWindow = wpfWindow;
}
#region IWindow Members
public virtual void Close()
{
this.wpfWindow.Close();
}
public virtual IWindow CreateChild(object viewModel)
{
var cw = new ContentWindow();
cw.Owner = this.wpfWindow;
cw.DataContext = viewModel;
WindowAdapter.ConfigureBehavior(cw);
return new WindowAdapter(cw);
}
public virtual void Show()
{
this.wpfWindow.Show();
}
public virtual bool? ShowDialog()
{
return this.wpfWindow.ShowDialog();
}
#endregion
protected Window WpfWindow
{
get { return this.wpfWindow; }
}
private static void ConfigureBehavior(ContentWindow cw)
{
cw.WindowStartupLocation = WindowStartupLocation.CenterOwner;
cw.CommandBindings.Add(new CommandBinding(PresentationCommands.Accept, (sender, e) => cw.DialogResult = true));
}
}
public static class PresentationCommands
{
private readonly static RoutedCommand accept = new RoutedCommand("Accept", typeof(PresentationCommands));
public static RoutedCommand Accept
{
get { return PresentationCommands.accept; }
}
}
Then we have a specialized window adapter for the MainWindow which ensures the DataContext property is initialized correctly with the ViewModel.
internal class MainWindowAdapter : WindowAdapter
{
private readonly ITrackerViewModelFactory vmFactory;
private bool initialized;
public MainWindowAdapter(Window wpfWindow, ITrackerViewModelFactory viewModelFactory)
: base(wpfWindow)
{
if (viewModelFactory == null)
{
throw new ArgumentNullException("viewModelFactory");
}
this.vmFactory = viewModelFactory;
}
#region IWindow Members
public override void Close()
{
this.EnsureInitialized();
base.Close();
}
public override IWindow CreateChild(object viewModel)
{
this.EnsureInitialized();
return base.CreateChild(viewModel);
}
public override void Show()
{
this.EnsureInitialized();
base.Show();
}
public override bool? ShowDialog()
{
this.EnsureInitialized();
return base.ShowDialog();
}
#endregion
private void DeclareKeyBindings(TrackerViewModel vm)
{
//this.WpfWindow.InputBindings.Add(new KeyBinding(vm.RefreshCommand, new KeyGesture(Key.F5)));
//this.WpfWindow.InputBindings.Add(new KeyBinding(vm.InsertProductCommand, new KeyGesture(Key.Insert)));
//this.WpfWindow.InputBindings.Add(new KeyBinding(vm.EditProductCommand, new KeyGesture(Key.Enter)));
//this.WpfWindow.InputBindings.Add(new KeyBinding(vm.DeleteProductCommand, new KeyGesture(Key.Delete)));
}
private void EnsureInitialized()
{
if (this.initialized)
{
return;
}
var vm = this.vmFactory.Create(this);
this.WpfWindow.DataContext = vm;
this.DeclareKeyBindings(vm);
this.initialized = true;
}
}
The Composition Root
And finally, you need a way to create the object graph. You are doing that in the correct place, but you are not doing yourself any favors by breaking it into many steps. And putting the container as an application-level variable is not necessarily a good thing - it opens up the container for abuse as a service locator.
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
// Begin Composition Root
var container = new StandardKernel();
// Register types
container.Bind<ISystemEvents>().To<MySystemEvents>();
container.Bind<ITrackerViewModelFactory>().To<TrackerViewModelFactory>();
container.Bind<Window>().To<MainWindow>();
container.Bind<IWindow>().To<MainWindowAdapter>();
// Build the application object graph
var window = container.Get<IWindow>();
// Show the main window.
window.Show();
// End Composition Root
}
}
I think the main issue you are having is that you need to ensure to call Show() on the MainWindow manually.
If you really do want to break the registration out into another step, you can do so by using one or more Ninject Modules.
using Ninject.Modules;
using System.Windows;
public class MyApplicationModule : NinjectModule
{
public override void Load()
{
Bind<ISystemEvents>().To<MySystemEvents>();
Bind<ITrackerViewModelFactory>().To<TrackerViewModelFactory>();
Bind<Window>().To<MainWindow>();
Bind<IWindow>().To<MainWindowAdapter>();
}
}
And then the App.xaml.cs file will look like this:
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
// Begin Composition Root
new StandardKernel(new MyApplicationModule()).Get<IWindow>().Show();
// End Composition Root
}
}
The trackerviewmodel will be instantiated by the auto-generated xaml designer code, not by ninject.
I've never used ninject, but I think you need to configure the container to know about your viewModel, and then inject the viewmodel for Ninject to resolve it and it's dependencies:
public class MainWindow : Window
{
[Inject]
public TrackerViewModel ViewModel { get; set; }
public MainWindow()
{
InitializeComponent();
DataContext = ViewModel;
}
}
I am working on a windows phone 8.1 universal app and want to find the best way of handling page navigations without having large amounts of logic in the code behind. I want to keep the code behind in my View as uncluttered as possible. What is the accepted MVVM way of navigating to a new page in response to a button click?
I currently have to send a RelayComnmand message from the ViewModel to the view with the details of the page to navigate to. This means that the code behind has to be wired up as follows:
public MainPage()
{
InitializeComponent();
Messenger.Default.Register<OpenArticleMessage>(this, (article) => ReceiveOpenArticleMessage(article));
...
}
private object ReceiveOpenArticleMessage(OpenArticleMessage article)
{
Frame.Navigate(typeof(ArticleView));
}
This just doesn't seem the best way although it does work. How can I do the page navigations directly from the ViewModel? I am using MVVM-Light in my project.
Ok, I have found an answer to this question. Took a bit of investigation but I eventually found the preferred MVVM-Light way of doing this. I don't take credit for this answer in anyway but just posting it here in case people are looking for an answer to this question.
Create an INavigationService interface as follows:
public interface INavigationService
{
void Navigate(Type sourcePageType);
void Navigate(Type sourcePageType, object parameter);
void GoBack();
}
Create a NavigationService class as follows:
public class NavigationService : INavigationService
{
public void Navigate(Type sourcePageType)
{
((Frame)Window.Current.Content).Navigate(sourcePageType);
}
public void Navigate(Type sourcePageType, object parameter)
{
((Frame)Window.Current.Content).Navigate(sourcePageType, parameter);
}
public void GoBack()
{
((Frame)Window.Current.Content).GoBack();
}
}
Now in the ViewModelLocator, set it up like this:
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance",
"CA1822:MarkMembersAsStatic",
Justification = "This non-static member is needed for data binding purposes.")]
public MainViewModel Main
{
get
{
return ServiceLocator.Current.GetInstance<MainViewModel>();
}
}
static ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
if (ViewModelBase.IsInDesignModeStatic)
{
SimpleIoc.Default.Register<INavigationService, Design.DesignNavigationService>();
}
else
{
SimpleIoc.Default.Register<INavigationService>(() => new NavigationService());
}
SimpleIoc.Default.Register<MainViewModel>();
}
Next setup a navigation service for design time as follows:
public class DesignNavigationService : INavigationService
{
// This class doesn't perform navigation, in order
// to avoid issues in the designer at design time.
public void Navigate(Type sourcePageType)
{
}
public void Navigate(Type sourcePageType, object parameter)
{
}
public void GoBack()
{
}
}
My MainViewModel constructor is as follows:
public MainViewModel(INavigationService navigationService)
{
_navigationService = navigationService;
...
Now you can simply use this to navigate in your viewmodel:
_navigationService.Navigate(typeof(WelcomeView));
For more details on the original author Laurent Bugnion see this article and associated code.
http://msdn.microsoft.com/en-us/magazine/jj651572.aspx
There is a new and simpler implementation here: https://marcominerva.wordpress.com/2014/10/10/navigationservice-in-mvvm-light-v5/
First we create the NavigationService and DialogService (for the page navigation params):
public ViewModelLocator() {
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
var navigationService = this.CreateNavigationService();
SimpleIoc.Default.Register<INavigationService>(() => navigationService);
SimpleIoc.Default.Register<IDialogService, DialogService>();
SimpleIoc.Default.Register<MainViewModel>();
SimpleIoc.Default.Register<DetailsViewModel>();
}
private INavigationService CreateNavigationService() {
var navigationService = new NavigationService();
navigationService.Configure("Details", typeof(DetailsPage));
// navigationService.Configure("key1", typeof(OtherPage1));
// navigationService.Configure("key2", typeof(OtherPage2));
return navigationService;
}
Then we create a RelayCommand and NavigationService in your ViewModel, like so:
public class MainViewModel : ViewModelBase {
private INavigationService _navigationService;
public RelayCommand<Tuple<string, string>> DetailsCommand { get; set; }
public MainViewModel(INavigationService navigationService) {
this._navigationService = navigationService;
DetailsCommand = new RelayCommand<Tuple<string, string>>((args) => NavigateTo(args));
}
public void NavigateTo(Tuple<string, string> args) {
this._navigationService.NavigateTo(args.Item1, args.Item1);
}
public void ClickAndNavigate() {
NavigateTo(new Tuple<string, string>("AdminPivotPage", "Test Params"));
}
}
And finally, we can get the page navigation params like so:
public sealed partial class DetailsPage : Page {
// ...
protected override void OnNavigatedTo(NavigationEventArgs e) {
var parameter = e.Parameter as string; // "My data"
base.OnNavigatedTo(e);
}
}
But to read the arguments passed in page navigation in MVVM pattern, you can take a look here.
I agree with ricochete above, its simpler, though my direct implimentation messed up with my Design Data Binding in Blend.
I decided to create an a class that inherited from the NavigationService
public class NavigationServiceHelper : NavigationService
{
public NavigationServiceHelper()
{
this.Configure("Page1", typeof(View.Page1));
this.Configure("Page2", typeof(View.Page2));
}
}
Then in the ViewModelLocator I registerred it this way
SimpleIoc.Default.Register<INavigationService, NavigationServiceHelper>();
My Design View Data Bindings worked again. If someone could explain why the design data wun't work in ricochete above, please do. Thank you!