The problem we are having is that we cannot get binding to work in our
prism silverlight application when using the view-model first
approach. The view first approach work fine. We have gone over the
official documentation and various web sites, but have still not
resolved the issue. Below is the code for both the view-model first,
and the view first approach. Are we missing something? Read about it on my blog http://silvercasts.blogspot.com
View-Model first approach:
Bootstrapper:
internal void RegisterLoginRegionAndView()
{
IRegionManager regionManager = Container.Resolve<IRegionManager>();
regionManager.RegisterViewWithRegion(ShellRegionNames.MainRegion,
() => Container.Resolve<IViewModel>().View);
}
ViewModel:
public ViewModel(IView view)
{
View = view;
View.SetModel(this);
User = new User();
User.Username = "TestUser";
}
ViewModel Interface:
public interface IViewModel
{
IView View { get; set; }
}
View Interface:
public interface IView
{
void SetModel(IViewModel model);
}
View Xaml:
<TextBox x:Name="Username" TextWrapping="Wrap" Text="{Binding User.Username}" />
View Code Behind:
public void SetModel(IViewModel viewModel)
{
this.DataContext = viewModel;
}
View first approach
Bootstrapper:
regionManager.RegisterViewWithRegion(ShellRegionNames.MainRegion, typeof(IView));
ViewModel:
public ViewModel()
{
User = new User();
User.Username = "TestUser";
}
View Code Behind:
public View(IViewModel viewModel)
{
InitializeComponent();
this.DataContext = viewModel;
}
Your implementation of SetModel on your view needs to be as follows:
public void MyUserControl : UserControl, IView
{
//...
public void SetModel(IViewModel vm)
{
this.DataContext = vm;
}
}
If that's not there, it needs to be (you haven't posted your implementation of SetModel, but this would be the source of the issue in this case).
If this is not the issue, it's likely because your ViewModel does not implement INotifyPropertyChanged. I usually use a base ViewModel that does this:
public class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
if(PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
And then all of my ViewModels derive from that:
public class MyViewModel : ViewModelBase
{
private User _user;
public User User
{
get { return _user; }
set
{
_user = value;
OnPropertyChanged("User");
}
}
}
Note: in your case the "User" object should probably also be a ViewModel and also raise OnPropertyChanged for the Username property.
Hope this helps.
The obvious difference to me is that you set the DataContext in the "view first" approach, but not in the "view model first" approach. I'm not sure if Prism sets the DataContext for you (I'd guess that you're assuming that it does) but try setting the DataContext manually to see if this is the problem. In your ViewModel constructor you call View.SetModel(this) - does that call set the DataContext?
The problem was that I was using the SetModel method before the data object was instanced. Moving it like this:
public ViewModel(IView view)
{
View = view;
User = new User();
User.Username = "TestUser";
View.SetModel(this);
}
solved the problem.
Related
I'm fairly novice with WPF. It's my understanding that data changes in the model, and it should notify the viewmodel, and the view will bind to properties and things alike in the viewmodel. Is this correct? If so, I've been reading that the model should implement INotifyPropertyChanged, and look something like this
public class LoginModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(string propName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
}
public bool Authenticated { get; set; }
}
and in my ViewModel, I have a property "AuthResult", that should get the update from the Model property "Authenticated"
public partial class view1 : UserControl, INotifyPropertyChanged{
public bool AuthResult
{
get
{
return _authVal;
}
set
{
_authVal = value;
NotifyPropertyChanged("AuthResult");
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(string propName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
}
}
I know this current implementation is incorrect. I've found that I should be subscribing to the PropertyChanged notification from my model like so:
LoginModel.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(LoginModel_PropertyChanged);
void LoginModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if(e.PropertyName == "Authenticated")
{
//do something
}
}
I don't see where the "AuthResult" property should be updated. Would I do something in the If statement like AuthResult = _model.Authenticated;?
EDITED:
and in my constructor?
LoginModel _model;
public view1(LoginModel model)
{
_model = model;
InitializeComponent();
}
If the model implements the INotifyPropertyChanged interface you can bind directly to it from the view:
<Button Content="Button" IsEnabled="{Binding Authenticated}" />
Note that the LoginModel class must raise the PropertyChanged event whenever the Authenticated property is set to a new value.
You could also expose the entire model entity through the view model class:
public class ViewModel
{
public ViewModel(LoginModel model)
{
Model = model;
}
public LoginModel Model { get; }
}
...and bind to it like this:
<Button Content="Button" IsEnabled="{Binding Model.Authenticated}" />
It is still the model class that must implement the INotifyPropertyChanged interface and raise change notifications.
Another option is for the view model to wrap any property of the model class that you want to be able to bind to from the view. Then you bind to a property of the view model class that in turn wraps a property of the model class something like this:
public class ViewModel
{
private readonly LoginModel _model;
public ViewModel(LoginModel model)
{
_model = model;
}
public bool AuthResult
{
get
{
return _model.Authenticated;
}
set
{
_model.Authenticated = value;
NotifyPropertyChanged("AuthResult");
}
}
}
<Button Content="Button" IsEnabled="{Binding AuthResult}" />
The benefit of using this latter approach is that view has no dependency upon the model class. It binds to the view model class only and this is how the MVVM design pattern typically is meant to be implemented.
But if you do bind to a (wrapper) property of the view model and want the view to be updated whenever a property of the model class is set, the model has to notify the view model that it has changed one way or another, i.e. it has to raise some kind of event or similar. And this typically means implementing the INotifyPropertyChanged interface. The view model can then subscribe to the PropertyChanged event of the model and raise its own PropertyChanged event for the data bound property whenever the model is updated, e.g.:
public class ViewModel
{
private readonly LoginModel _model;
public ViewModel(LoginModel model)
{
if (model == null)
throw new ArgumentNullException("model");
_model = model;
_model.PropertyChanged += OnModelChanged;
}
private void OnModelChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "Authenticated")
NotifyPropertyChanged("AuthResult");
}
public bool AuthResult
{
get
{
return _model.Authenticated;
}
set
{
_model.Authenticated = value;
NotifyPropertyChanged("AuthResult");
}
}
}
Just use Model as member in the ViewModel
public class ViewModel
{
private Model _myModel;
public Model MyModel
{
get { return _myModel; }
set
{
if (Equals(_myModel, value)) return;
_myModel = value;
NotifyPropertyChanged(nameof(MyModel));
}
}
}
Then in xaml you can bind properties of Model
<CheckBox IsChecked="{Binding MyModel.Authenticated}" />
With this approach your ViewModel will be "build" around your Model.
In case you don't want that models implement INotifyPropertyChanged than create a "Facade" class of model in use it in same way as previous example.
public class ModelFacade : INotifyPropertyChanged
{
private Model _myModel;
public bool Authenticated
{
get { return _myModel.Authenticated; }
set
{
_myModel.Authenticated = value;
NotifyPropertyChanged(nameof(Authenticated));
}
}
}
public class ViewModel
{
private ModelFacade _myModel;
public ModelFacade MyModel
{
get { return _myModel; }
set
{
if (Equals(_myModel, value)) return;
_myModel = value;
NotifyPropertyChanged(nameof(MyModel));
}
}
}
I have the following scenario:
I have a user control, let's say UserControl.xaml
In the code behind of this control I have the method DoSomething()
I have viewmodel for this control UserControlViewModel.cs
I need to call usercontrol's DoSomething() method somewhere. Any ideas how to accomplish this?
Thanks!
If I really had to do this, then using the DataContextChanged event may help.
Here's a solution with hopefully minimal coupling between the view and the view-model.
public partial class MainWindow : IMainWindow
{
public MainWindow()
{
this.DataContextChanged += this.MainWindowDataContextChanged;
this.InitializeComponent();
}
private void MainWindowDataContextChanged(object sender,
DependencyPropertyChangedEventArgs e)
{
var vm = this.DataContext as IMainWindowViewModel;
if (vm != null)
{
vm.View = this;
}
}
public void DoSomething()
{
Debug.WriteLine("Do something in the view");
}
}
public interface IMainWindow
{
void DoSomething();
}
public class MainWindowViewModel : IMainWindowViewModel
{
public MainWindowViewModel()
{
this.DoSomethingCommand = new RelayCommand(this.DoSomething);
}
public ICommand DoSomethingCommand { get; set; }
private void DoSomething()
{
Debug.WriteLine("Do something in the view model");
var view = this.View;
if (view != null)
{
view.DoSomething();
}
}
public IMainWindow View { get; set; }
}
public interface IMainWindowViewModel
{
IMainWindow View { get; set; }
}
You really should be using an MVVM framework if you're doing MVVM. A framework would provide a mechanism from which you can invoke a verb (method) on your view model from your view. Caliburn.Micro for example provides Actions.
It sounds as though your application is incorrectly structured.
What does
DoSomething()
do, that isn't reacting to a change in a bound property of the ViewModel?
If you really need to trigger something in the code behind of the View from the ViewModel, use a messaging handler such as the one in the Galasoft MVVMLight framework.
I am new to MVVM and WPF.
I am using MVVM Light to make an application which contains a DataGrid within a window, which has a view model (MainViewModel) and another window for adding and editing records in the DataGrid, that also has its own view model (EditViewModel).
What I am worried about is the approach I am using to open the Add/Edit window from the MainViewModel. In the MainViewModel I have a property SelectedItem, which is bound to the SelectedItem property of the DataGrid and an IsEdit boolean property that indicates if the Add/Edit window should be launched in Add or Edit mode.
When the Add/Edit window gets opened in edit mode, in the constructor of its view model I have the following line:
MainViewModel mainViewModel = ServiceLocator.Current.GetInstance<MainViewModel>();
That obviously retrieves the current instance of the MainViewModel, which works perfectly fine, but I am not really sure it is the best way to do this.
Also if I have more than one instances of the Main window, that use the same MainViewModel instance and I open an instance of the Add/Edit window from both of them, the Add/Edit windows are going to get data from the same instance of the MainViewModel which may be a problem.
If I try to create a new instance of MainViewModel for each MainWindow I open, then I don't know how to pass the instance of the currently used MainViewModel to the EditViewModel.
I hope I made clear what I need to do. Tell me if I have missed something and I will add it:)
Thanks in advance
Hi if I havent misunderstood your problem incorrect you can do it this way:
Since i need IsRequired dependency Property in both MainView and EditView i created a class that extends Window class
public class ExtendedWindow:Window
{
public static readonly DependencyProperty IsRequiredProperty = DependencyProperty.Register("IsRequired", typeof(bool), typeof(ExtendedWindow));
public bool IsRequired
{
get { return (bool)GetValue(IsRequiredProperty); }
set { SetValue(IsRequiredProperty, value); }
}
}
MainView and ViewModel
public partial class MainWindow:ExtendedWindow
{
public MainWindow()
{
InitializeComponent();
DataContext = new MainViewModel();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
EditView editView = new EditView();
**((EditViewModel)editView.DataContext).IsRequired = this.IsRequired;**
editView.Show();
}
}
public class MainViewModel : INotifyPropertyChanged
{
public MainViewModel()
{
IsRequired = true;
}
private bool isRequired;
public bool IsRequired
{
get { return isRequired; }
set { isRequired = value; Notify("IsRequired"); }
}
public event PropertyChangedEventHandler PropertyChanged;
private void Notify(string propName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
EditView and ViewModel
public partial class EditView:ExtendedWindow
{
public EditView()
{
InitializeComponent();
DataContext = new EditViewModel();
}
}
public class EditViewModel : INotifyPropertyChanged
{
private bool isRequired;
public bool IsRequired
{
get { return isRequired; }
set { isRequired = value; Notify("IsRequired"); }
}
public event PropertyChangedEventHandler PropertyChanged;
private void Notify(string propName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
This is just kind of dummy but can give you idea how you can do it. I have tried it in dummy and its working fine.
we mvvm lovers all know Josh Smith mvvm sample and how he has saved the customer in the detail customer view by injecting the repository object into the customerViewModel`s constructor.
But a viewmodel should not know about repositories. Its just a model of a view nothing must being aware of persistence etc...
How can I register my Action delegate SaveDocumentDelegate on the DocumentViewModel if its set in the code-behind? Actually I should subscribe the delegate in my DocumentController but how can I instantiate the DocumentView in my DocumentController and set it as Datacontext not doing that in code-behind. Only thing that came to my mind is using a contentcontrol in the window and bind it to the type of the viewModel and datatemplate it with the Document UserControl like this:
<UserControl.Resources>
<DataTemplate DataType="{x:Type ViewModel:DocumentViewModel}">
<View:DocumentDetailView/>
</DataTemplate>
</UserControl.Resources>
<ContentControl Content="{Binding MyDocumentViewModel}" />
But I do not want to use a control to solve my architectural problems...
xaml:(view first approach)
public partial class DocumentDetailView : UserControl
{
public DocumentDetailView()
{
InitializeComponent();
this.DataContext = new DocumentViewModel(new Document());
}
}
DocumentViewModel:
public class DocumentViewModel : ViewModelBase
{
private Document _document;
private RelayCommand _saveDocumentCommand;
private Action<Document> SaveDocumentDelegate;
public DocumentViewModel(Document document)
{
_document = document;
}
public RelayCommand SaveDocumentCommand
{
get { return _saveDocumentCommand ?? (_saveDocumentCommand = new RelayCommand(() => SaveDocument())); }
}
private void SaveDocument()
{
SaveDocumentDelegate(_document);
}
public int Id
{
get { return _document.Id; }
set
{
if (_document.Id == value)
return;
_document.Id = value;
this.RaisePropertyChanged("Id");
}
}
public string Name
{
get { return _document.Name; }
set
{
if (_document.Name == value)
return;
_document.Name = value;
this.RaisePropertyChanged("Name");
}
}
public string Tags
{
get { return _document.Tags; }
set
{
if (_document.Tags == value)
return;
_document.Tags = value;
this.RaisePropertyChanged("Tags");
}
}
}
UPDATE:
public class DocumentController
{
public DocumentController()
{
var win2 = new Window2();
var doc = new DocumentViewModel(new DocumentPage());
doc.AddDocumentDelegate += new Action<Document>(OnAddDocument);
win2.DataContext = doc;
wind2.ShowDialog();
}
private void OnAddDocument(Document doc)
{
_repository.AddDocument(doc);
}
}
What do you think about that idea?
But a viewmodel should not know about
repositories. Its just a model of a
view nothing must being aware of
persistence etc...
The viewmodel connects the model and view together; it is exactly what controls persistence, though it does not handle persistence.
We decouple this from other concern by using services.
One way to avoid adding persistence concerns to the viewmodel is by abstracting those concerns into repository interfaces, so that we can inject it as a dependency. In this way we can delegate persistence work in the viewmodel, usually in response to the user's interaction with the view.
How do I close a View from its ViewModel?
I've a WPF window which has defined multiple Regions and being used as a Shell to host views for my application. I would like to have a View able to remove itself from the Region, or close it from a tabbed container. How can I accomplish this behavior from ViewModel.
Since your ViewModel doesn't (and shouldn't) have a reference to the View, you can't close it directly. However, what you can do is add an Event in your ViewModel to indicate that it wants to be closed.
Josh Smith has written an article showing how to do this (about halfway through the article).
This really depends on your app architecture, but here's how I do it with Prism.
First I want to say, it is ok to have your VM reference the View just as long as it is not a concrete implementation of the View, ie, references by interface.
I marry the View and ViewModel using dependency injection, very similar to how it's done in the StockTraderRI. So I have an IView and an IViewModel. IViewModel has a propery called "View" of type IView.
From the code layer (for me, usually the controller...see StockTraderRI) that works with your regions, add the mechanism to remove your view from the region.
For example:
myRegion.Remove(myIViewModel.View);
If regions are handled by a controller, you may want to put a simple event on the VM to notify when a VM wants to be "closed". You can also experiment with the IEventAggregator if you wish to use a weak eventing model. If the region is handled in the VM, simply add that code there.
This how my Login module looks like:
public class LoginModule : IModule
{
private readonly IUnityContainer container;
public LoginModule(IUnityContainer container)
{
this.container = container;
}
#region IModule Members
public void Initialize()
{
this.container.RegisterType<ILoginController, LoginController>(new ContainerControlledLifetimeManager());
this.container.RegisterType<ILoginView, LoginView>();
this.container.RegisterType<ILoginViewModel, LoginViewModel>();
ILoginController controller = this.container.Resolve<ILoginController>();
controller.Run();
}
#endregion
}
This is the controller:
public class LoginController : ILoginController
{
private readonly IRegionManager regionManager;
private readonly ILoginViewModel model;
public LoginController(IRegionManager regionManager, ILoginViewModel model)
{
this.regionManager = regionManager;
this.model = model;
model.RequestClose += new EventHandler(model_RequestClose);
}
void model_RequestClose(object sender, EventArgs e)
{
regionManager.Regions["LoginRegion"].Remove(model.View);
}
#region ILoginController Members
public void Run()
{
// Register views here
regionManager.Regions["LoginRegion"].Add(model.view);
}
#endregion
}
And this is my ViewModel:
public class LoginViewModel : ViewModelBase, ILoginViewModel
{
IEventAggregator _eventAggregator;
RelayCommand _loginCommand;
private readonly UserProfileRepository _userProfileRepository;
public event EventHandler RequestClose;
public ICommand LoginCommand
{
get
{
if (_loginCommand == null)
{
_loginCommand = new RelayCommand(
param => this.Login(),
param => this.IsValid());
}
return _loginCommand;
}
}
public LoginViewModel(IEventAggregator eventAggregator, UserProfileRepository userProfileRepository, ILoginView view)
{
this._eventAggregator = eventAggregator;
this._userProfileRepository = userProfileRepository;
this.View = view;
}
#region ILoginViewModel Members
public ILoginView View { get; private set; }
#endregion
}