Sharing data between different ViewModels - c#

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>

Related

WPF MVVM Button from View control interface

I'm pretty new to WPF and MVVM concept and i'm trying to solve probably stupid issue. I have MainViewModel where I control what should be seen on the screen according to pressed buttons in the menu.
class MainViewModel : ObservableObject
{
public RelayCommand HomeViewCommand { get; set; }
public RelayCommand SettingsViewCommand { get; set; }
public HomeViewModel HomeVM { get; set; }
public SettingsViewModel SettingsVM { get; set; }
private object _currentView;
public object CurrentView
{
get { return _currentView; }
set
{
_currentView = value;
OnPropertyChanged();
}
}
public MainViewModel()
{
HomeVM = new HomeViewModel();
SettingsVM = new SettingsViewModel();
CurrentView = HomeVM;
HomeViewCommand = new RelayCommand(o =>
{
CurrentView = HomeVM;
});
SettingsViewCommand = new RelayCommand(o =>
{
CurrentView = SettingsVM;
});
}
One of my Views is SettingsView. In this View I have a button, which should check if the connection string is allright. And because I am going to use kinda lot SQL commands my thought was, to put all code regarding SQL into one folder. So basically the project is MVVM(file)>View(file),ViewModel(file).... and SQL(file)>....
Sadly when I add to the SettingsView sql, the app falls because of 'Object reference not set to an instance of an object'
In the SettingsView is:
public partial class SettingsView : UserControl
{
private readonly HSQLTestConnection _SQLTestConnection;
public SettingsView(HSQLTestConnection SQLTestConnection)
{
InitializeComponent();
_SQLTestConnection = SQLTestConnection;
And button is like this:
_SQLTestConnection.TryConnectionString(ConnectionString);
Model is empty:
class SettingsViewModel
{
public SettingsViewModel()
{
}
}
Interface for SQL is:
public interface HSQLTestConnection
{
void TryConnectionString(string ConnectionString);
}
And SQL function:
public class SQLTestConnection : HSQLTestConnection
{
public void TryConnectionString(string ConnectionString)
{
//do something
}
}
App does not show any error and was working and changing Views pretty fine, I think the issue is with public SettingsView(HSQLTestConnection SQLTestConnection) But I could not find how to solve this.
Since I am going to have multiple classes for SQL, I wanted to solve it this way. It used to work in different app I wrote, but I was not using RellayCommand, which I wanted to try.
Thank you for your help in advance.
I see that SettingsView class extends the UserControl class. This is problematic because
you say you want to follow the MVVM design pattern but your user control code (SettingsView) has a reference to your database connection (HSQLTestConnection) in the constructor. You should not mix your view code with your database code.
your SettingsView is initialized by the framework so where is it supposed to get the value for the HSQLTestConnection parameter in the constructor?
In any case, your view should not have any database logic in it, at least not if you want to follow MVVM.
What you could do is to initiate your database connection in the view model of the settings view SettingsViewModel. Not great, but somewhat better.
Since you mentioned there will be "kinda lot SQL commands", I would suggest you separate this code into a dedicated service, and then use this service in your view models where applicable.
public interface IMyDatabaseService
{
bool TestConnection();
IEnumerable<SomeDataObject> GetData();
...
}
You would then pass this interface where needed:
public class SettingsViewModel : INotifyPropertyChanged
{
private readonly IMyDatabaseService databaseService;
private bool connectionSuccessful;
public RelayCommand TestConnectionCommand { get; set; }
public bool ConnectionSuccessful
{
get => connectionSuccessful;
set
{
connectionSuccessfull = value;
var propertyName = nameof(ConnectionSuccessful);
PropertyChanged?.Invoke(this, new (propertyName));
}
}
public SettingsViewModel(IMyDatabaseService databaseService)
{
this.databaseService = databaseService;
TestConnectionCommand = new RelayCommand(_ =>
ConnectionSuccessful = databaseService.TestConnection()
);
...
}
}
public class MainViewModel
{
...
public MainViewModel()
{
...
IMyDatabaseService databaseService = new MyDatabaseService();
SettingsVM = new SettingsViewModel(databaseService);
...
}
...
}
Notice the TestConnectionCommand as well as the ConnectionSuccesful boolean.
The command will call your database service and this is what you will bind your button to.
Similarly, the boolean can be bound to in your view to show the connection state. Since this value can change whenever you run the command, you have to invoke PropertyChanged to let the framework know the value has changed. In this case, the invocation is done in the setter.
Assuming your data context is set correctly, in your SettingsView view you would now have:
...
<Button Command="{Binding TestConnectionCommand}"> Test </Button>
<TextBlock Text="Connection failed!">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Style.Triggers>
<DataTrigger Binding="{Binding ConnectionSuccessfull}" Value="True">
<Setter Property="Text" Value="Connection successful!" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
...
I used a text block with a data trigger to show the connection state, but you can use the boolean and the data trigger to do whatever you wish. Maybe show a modal dialog or something.
Better still would be to use some sort of dependency injection to inject your database service and other dependencies as well as making the database code async so that your UI won't freeze, but that will be for the future you to figure out.

How to handle dependency injection with WPF with multiple pages and navigation?

I've been trying to do the following thing in WPF:
A window with a login-page and a home-page.
Upon successfully authenticating a user, the window should display the home-page.
It should work by using the native WPF dependency injection framework.
But also...
There might be a page 3, 4, 5 and each of these pages should be able to call one another.
And maybe each of these pages could have pages inside them that can also call each other.
So the solution should be able to work with nested pages and navigations if possible.
What I have:
So, after looking for solutions in the stack forum I ended up with this composition approach.
Starting by the App.xaml, all services and viewmodels are initialized and the main window receives its viewmodel by injection:
private void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<MainWindow>();
//ViewModels
services.AddSingleton<MainViewModel>();
services.AddSingleton<AuthViewModel>();
services.AddSingleton<HomeViewModel>();
}
private void OnStartup(object sender, StartupEventArgs e)
{
var mainWindow = serviceProvider.GetService<MainWindow>();
mainWindow.DataContext = serviceProvider.GetService<MainViewModel>();
mainWindow.Show();
}
Then, the mainViewModel receives by injection every other viewmodel and stores them in a property.
public class MainViewModel
{
public IPageViewModel SelectedPage {get; set; } //PropertyChanged() removed for brevity.
public ObservableCollection<IPageViewModel> Pages {get; set;}
public MainViewModel(AuthViewModel authViewModel, HomeViewModel homeViewModel)
{
this.Pages = new ObservableCollection<IPageViewModel>() { authViewModel, homeViewModel};
this.SelectedPage = this.Pages.First();
}
}
All page viewmodels inherit from this interface so they can be retrieved from the collection by name and then added as the SelectedPage when needed.
public interface IPageViewModel : INotifyPropertyChanged
{
public string PageTitle { get; set; }
}
The window has a content control with a property content bound to the SelectedPage so it's updated.
<Window>
<ContentControl Content="{Binding SelectedPage}" />
</Window>
And it knows which view to use for each viewmodel by these data templates.
<Application.Resources>
<DataTemplate DataType="{x:Type vm:AuthViewModel}">
<views:AuthView />
</DataTemplate>
<DataTemplate DataType="{x:Type vm:HomeViewModel}">
<views:HomeView />
</DataTemplate>
</Application.Resources>
But then... I noticed that this won't work, I can only call changes on the SelectedPage from within the mainViewModel.
public class AuthViewModel : BaseViewModel
{
public AuthViewModel() { }
public void AttemptLogin() {
// how
SelectedPage = Pages[1];
}
}
Issues
I could perhaps inject the mainviewmodel in all child models, but that would not look good and in fact from the start a lot of things are kind of a mess.
For example, I have to:
Add a service viewmodel for every viewmodel I create to the app.xaml.
Add each one of them as a parameter of the mainwindow viewmodel which looks ugly.
I'm probably doing this very wrong, I need help.
There are many possible solutions. A simple one is to introduce an event.
I also recommend to move and restrict the responsibility to select view models to the MainViewModel. Other page models should not be aware of the flow like who selects who. Otherwise this would add a too tight coupling, which is avoidable at this point.
public class MainViewModel
{
public IPageViewModel SelectedPage { get; set; }
private Dictionary<string, IPageViewModel> Pages { get; }
public MainViewModel(AuthViewModel authViewModel, HomeViewModel homeViewModel)
{
authViewModel.AuthenticationPassed += OnAuthenticationSuccessfull;
this.Pages = new Dictionary<string, IPageViewModel>()
{
{ nameof(AuthViewModel), authViewModel },
{ nameof(HomeViewModel), homeViewModel }
};
this.SelectedPage = this.Pages[nameof(AuthViewModel)];
}
public OnAuthenticationSuccessfull(object sender, EventArgs e)
{
(sender as AuthViewModel).AuthenticationPassed -= OnAuthenticationSuccessfull;
this.SelectedPage = this.Pages[nameof(HomeViewModel)];
}
}
class AuthViewModel
{
public event EventHandler AuthenticationPassed { get; }
...
}

Multiple ViewModels in same View

I have several different ViewModels that I would like to display in the same view (MainPage.xaml).
I'm new to this and don't know how to do it. I have tried to create a MainViewModel:
public class MainViewModel : ViewModelBase, INotifyPropertyChanged
{
WeatherViewModel weatherView = new WeatherViewModel();
ForecastViewModel forecastViewModel = new ForecastViewModel();
DeparturesViewModel departuresViewModel = new DeparturesViewModel();
CalenderViewModel calenderViewModel = new CalenderViewModel();
}
public void GetAllViews()
{
weatherView.GetCurrentTemp();
forecastViewModel.GetForecastTemp();
departuresViewModel.GetDepartures();
calenderViewModel.GetCalender();
}
And in my MainPage.xaml.cs I have this:
public MainPage()
{
this.InitializeComponent();
this.DataContext = new MainViewModel();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
var vm = this.DataContext as MainViewModel;
vm.GetAllViews();
}
I manage to display each ViewModel individually like this instead:
this.DataContext = new WeatherViewModel();
but I would like to display everything in the same View.
I think you're on the right track but missed some small but important pieces.
In your example code the MainViewModel class is currently setup with private fields where you really need public properties. Additionally, I would make sure ViewModelBase implements INotifyPropertyChanged if it's not already; that way none of the classes deriving from ViewModelBase need to worry about that part.
public abstract class ViewModelBase : INotifyPropertyChanged
{
/* INotifyPropertyChanged implementation +
whatever other common behavior makes sense
belongs in this class
*/
}
public class MainViewModel : ViewModelBase
{
public WeatherViewModel Weather { get; } = new WeatherViewModel();
public ForecastViewModel Forecast { get; } = new ForecastViewModel();
public DeparturesViewModel Departures { get; } = new DeparturesViewModel();
public CalendarViewModel Calendar { get; } = new CalendarViewModel();
}
In your view code behind file you're setting the data context to 2 different instances of MainViewModel - once in the constructor and once in the Loaded event handler. I'd stick with the constructor version or instead you could set the data context in XAML like this:
<MainPage.DataContext>
<MainViewModel>
</MainPage.DataContext>
Once the data context for the main page is setup and the view models are public properties then you can use bindings to access the state (properties) of the view models perhaps something like this:
<TextBlock Text='{Binding Path=Weather.CurrentTempCelsius, StringFormat='Current Temp: {0}°C'}' />
Multiple ViewModels in same View
You have many ways to approach. Fist way using x:bind. You could initialize each view model in the page resource and give them x:Name, then using x:bind to access specific property like following.
<Page.Resources>
<local:CalenderViewModel x:Name="CalenderViewModel"/>
<local:DeparturesViewModel x:Name="DeparturesViewModel"/>
<local:ForecastViewModel x:Name="ForecastViewModel"/>
<local:WeatherViewModel x:Name="WeatherViewModel"/>
</Page.Resources>
<Grid>
<TextBlock Text="{x:Bind WeatherViewModel.temperature}"/>
</Grid>
Other Way is that integrate all the ViewModels into MainViewModel. And coding.monkey provide the correct solution that you could refer directly.

Parameterless View Constructor In Prism 6

Here's what I'm trying to do (and there may be a better way):
My application is meant to keep track of players in a game. As players join the game events will be sent (using the event aggregator) to create a user control and add it to a List which is connected to an ItemControl. When they leave the game, events will be sent to remove the user control from the list.
The actual ItemContol looks like this - the Players binding is to the List so that it can show the individual player user controls:
<UserControl>
<Grid>
<ScrollViewer VerticalScrollBarVisibility="Auto">
<ItemsControl ItemsSource="{Binding Players}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<local:PlayerListView />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
</Grid>
</UserControl>
This is inserted into a grid row/column of the main window view just by using the below command:
<views:PlayerListView />
The issue I am running into is this last line <views:PlayerListView /> as it is saying that "There are no accessible PlayerListView constructors". Here is the code behind with the constructor and I believe the reason I am getting this error is because the constructor isn't parameterless -- here is the code-behind.
public partial class PlayerListView : UserControl
{
public PlayerListView(IEventAggregator eventAggregator)
{
InitializeComponent();
DataContext = new PlayerListViewModel(eventAggregator);
}
}
I need the PlayerListViewModel to have the IEventAggregator in its constructor but am not sure the appropriate way to do it. I've viewed this Stack Overflow post: Prism MVVM - How to pass an IEventAggregator to my ViewModel but am not sure if that is the best way to achieve what I am trying to do or not and am slightly confused on how I would incorporate it.
Adding PlayerListViewModel
namespace PlayerTools.ViewModels
{
class PlayerListViewModel
{
#region Private Fields
IEventAggregator _eventAggregator;
#endregion
#region Public Commands
ICommand AddPlayerToListCommand { get; set; }
ICommand RemovePlayerFromListCommand { get; set; }
#endregion
public List<PlayerStackPanelViewModel> Players = new List<PlayerStackPanelViewModel>();
#region Constructor
public PlayerListViewModel(IEventAggregator eventAggregator)
{
_eventAggregator = eventAggregator;
Players.Add(new PlayerStackPanelViewModel()
{
PlayerName = "Steven",
PlayerClass = "Tennis",
CurrentLevel = 10,
NumberOfDeaths = 0
});
Players.Add( new PlayerStackPanelViewModel()
{
PlayerName = "Steven",
PlayerClass = "Soccer",
CurrentLevel = 17,
NumberOfDeaths = 1
});
//Commands
AddPlayerToListCommand = new DelegateCommand<PlayerStackPanelViewModel>(AddPlayerToList);
RemovePlayerFromListCommand = new DelegateCommand<string>(RemovePlayerFromList);
}
#endregion
public void AddPlayerToList(PlayerStackPanelViewModel player)
{
Players.Add(player);
}
public void RemovePlayerFromList(string playerName)
{
Players.Remove(Players.Single(s => s.PlayerName == playerName));
}
}
}
You could use the ViewModelLocator to wire the DataContext of a view to an instance of your view model:
PlayerListView.xaml.cs:
public partial class PlayerListView : UserControl
{
public PlayerListView()
{
InitializeComponent();
}
}
PlayerListView.xaml:
<UserControl ... prism:ViewModelLocator.AutoWireViewModel="True" />
Your use of the event aggregator should be implemented in the view model and not in the view.

Mvvm model ViewModel

It can be named MVVM model or not? Because View interacts with DataModel through
ViewModelData. Does View should interact only with ViewModelData? I did read somewhere that right MVVM model should implement INotify in ViewModel not in Model. Is it right?
namespace WpfApplication135
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModelData();
}
}
public class ViewModelData
{
public DataModel DM { get; set; }
public ViewModelData()
{
DM = new DataModel();
}
}
public class DataModel : INotifyPropertyChanged
{
public int label;
public int Label
{
get
{
return label;
}
set
{
label = value;
RaisePropertyChanged("Label");
}
}
public DataModel()
{
Action Update = new Action(Run);
IAsyncResult result = Update.BeginInvoke(null, null);
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string info)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
public void Run()
{
int i=0;
while(true)
{
System.Threading.Thread.Sleep(2000);
Label = ++i;
}
}
}
}
xaml
<Grid>
<Label Content="{Binding DM.Label}" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top"/>
</Grid>
The initial thought for MVVM was indeed that the View should not know (not depend on) the Model.
In practice this meant re-implementing all those Model properties in the ViewModel (see the light-yellow box in the picture below), a lot of work. And extra painful when your Model can easily implement INPC, for example when it is generated from a database schema. Entity Framework in database-first mode lets you inject the INPC code through the T4 templates.
The consensus quickly became that it is OK to forward a ViewModel.Model property and bind to that, just like your DM property. See the light-blue box in the picture.
The issue is visualized well in this picture, note the large number of arrows in the top right corner. They depict the various solutions for databinding and you can use any combination of them.
One point of MVVM is that your view should not know your data model and vice versa. That's why there is a ViewModel. Right now, your ViewModel is wasted code. It does nothing.
You may want to read up on MVVM a bit more, because explaining it is way too broad for the Q&A format here.

Categories

Resources