MVVM child->parent refrence

I am modelling icons on a canvas. So I have Canvas which owns icons

The canvas has information such as its scale, Pixels Per Meter, for scaled icon sizes and the amount of degrees it has been rotated.

I currently have it set up with the icons having a reference to the canvas object so they can grab the information via a property. This way I don’t have to write code to update each icon when any of those items change. The icons detect the change themselves.

Is this the best way to do it or is there a better way to loosen the coupling?

Отмена изменений объекта MVVM WPF EF6

У меня есть проект для моего колледжа. В нем я пытаюсь реализовать MVVM + WPF + EF6. По ходу возникла проблема, которую я не могу решить уже слишком долго.

Немного о том что я уже смог сделать:

Есть класс MedRecordViewModel – view model с свойством selecteditem и определёнными CRUD командами, есть view MedRecordEdit в которую передаётся в качестве datacontexts’a – MedRecordViewModel.


Суть проблемы: Я не могу сделать отмену изменений, которые сразу же применяются из-за реализованного inotifypropertychanged интерфейса.

Я нашел решение по типу “создать клон объекта с помощью AutoMapper’a и в случае отмены просто перезаписать в текущий selecteditem созданный клон”, но из-за того что автомапер создает полностью новый объект, этот объект судя по всему перестает отслеживаться моей ObservableCollection.


  1. Как правильно делать отмену изменений ?
  2. Как померить automapper с EF?

Colorear filas según condición WPF MVVM

estoy trabajando con WPF y MVVM y estoy teniendo un problema al querer usar un enum para determinar el color de las filas de un DataGrid.

Tengo un ViewModel que se ve más o menos así

public class DespieceViewModel : BaseViewModel {     private readonly ObservableCollection<ArticuloItemViewModel> mItemList;         public ICollectionView<ArticuloItemViewModel> Items { get; }      public DespieceViewModel()     {         //Acá iría la lógica con la que lleno mItemList         Items = new MyCollectionViewGeneric<ArticuloItemViewModel>(CollectionViewSource.GetDefaultView(mItemList));                 } } 

Aclaro que la implementación de ICollectionView<T> existe sólo para tener IntelliSense en XAML, no tiene ningún cambio con la original, de todos modos dejo el enlace a la clase en github por las dudas

El ViewModel ArticuloItemViewModel es sencillo, sería algo así

public class ArticuloItemViewModel : BaseViewModel {         public string CodigoPadre { get; set; }     public string CodigoDelfos { get; set; }     public EstadoArticuloDespiece Estado { get; set; }         } 

El enum EstadoArticuloDespiece sería el siguiente:

public enum EstadoArticuloDespiece {     Ok,     Inexistente,     Duplicado } 

Para este enum tengo un pequeño Converter que simplemente usa un switch y devuelve un SolidColorBrush según cual es el valor.

Teniendo en cuenta esto, estoy intentando Bindear el color de fila de un DataGrid basados en EstadoArticuloDespiece

Lo hago de la siguiente manera (basándome en esta respuesta):

<DataGrid ItemsSource="{Binding Items}" >     <DataGrid.RowStyle>         <Style TargetType="DataGridRow">             <Setter Property="Background">                 <Setter.Value>                     <SolidColorBrush Color="{Binding Path=Estado, Converter={StaticResource EstadoToBrushValueConverter}}"/>                 </Setter.Value>             </Setter>         </Style>     </DataGrid.RowStyle>     <DataGrid.Columns>         <DataGridTextColumn Header="Código Padre" Binding="{Binding Path=CodigoPadre}"></DataGridTextColumn>         <DataGridTextColumn Header="Código Delfos" Binding="{Binding Path=CodigoDelfos}"></DataGridTextColumn>     </DataGrid.Columns> </DataGrid> 

Las columnas con su información se muestran sin problemas, pero el color no cambia y ReSharper me marca error en Color="{Binding Path=Estado}" diciéndome:

Cannot resolve property Estado in data context of type..

¿En qué estoy fallando? ¿Cómo debe bindearse esta propiedad?

Aclaro que BaseViewModel implementa PropertyChanged para todas las propiedades.

When not to use View Services in MVVM design pattern?

I’m using the MVVM design pattern in my application which is comprised of,

  • A Xamarin.IOs project (View Layer)
  • A Net Standard project (Common Layer)
  • A Xamarin.Android project (in the future) (View Layer)

In the Xamarin.IOs project, there’s a Delegate class (NotificationCenterDelegate extending UNUserNotificationCenterDelegate) which triggers a method (WillPresentNotification) on receiving a notification. This method should inform a ViewModel (BasePageViewModel) that the method was invoked. The BasePageViewModel is not injected to the Delegate class.

There’s a couple of approaches I can use here,

  1. Inject a ViewModel (ControlViewModel). Then invoke a method in the ViewModel from the WillPresentNotification method.

    public void WillPresentNotification(/* parameters */) {     ControlViewModel.UpdateCount(); } 

    In ControlViewModel I invoke an event that is captured and handled in BasePageViewModel

  2. Implement an Interface (IDelegateViewService) in the Delegate class that has an Event Handler. Trigger the event in the WillPresentNotification method.

    public class NotificationCenterDelegate : UNUserNotificationCenterDelegate, INotificationCenterDelegate {     public void WillPresentNotification(/* parameters */)     {         CountUpdated?.Invoke(this, null);     } }  public interface IDelegateViewService {     event EventHandler CountUpdated; } 

    Then capture handle the event in the BasePageViewModel.

I prefer the first approach as it doesn’t use an interface to invoke something in the ViewModel. Because as I feel using ViewServices reduces the ability of sharing code among different platforms. And I feel ViewServices should be only used if it’s the only approach available.

Can anyone comment on these two design approaches? I would like to get some theory involving why one is better than the other or why a completely different design is much better!

MVVM viewmodel to view correlation in adaptive UI

I am making an mvvm application for the uwp platform and I am looking for advice on the following matter.

Take for example the windows 10 e-mail application, which when full screen displays both the e-mail list and e-mail content in one page, while in smaller form factors the content is displayed in separate pages.

What is the best way to correlate views with viewmodels in this scenario?

My thoughts are

  1. A big view model which will be the data context for all the views in this scenario.

  2. Two view models, one for the e-mail list and one for the e-mail content, set as the data context for different parts of the page or different pages.

  3. Three view models. The two view models from the previous point and another one to coordinate them.

What do you think is best? My problem mostly stems from the fact that in one case you actually navigate to another page, and have to put logic in navigation events that don’t exist in the other case.

Mvvm pattern android – Java

I’m starting MVVM pattern and would like to know if I’m doing well with this. Here is the link from my repository on GitHub:

Does my application even implement MVVM? Are there any suggestions or opinions about my code? How am I going?

Bellow a quick example of how I’m doing. Please see my application in my repository, it’s just a simple project.

binding.getViewModel().getAllUsers().observe(this, new Observer<List<User>>() {     @Override     public void onChanged(@Nullable List<User> pessoas) {         //update recyclerview when my list my database that returns liveData is changed         userAdapter.addUserToList(pessoas);     } }); 

Addition Program using wpf through MVVM

I’m new to MVVM and WPF. Please suggest whether this is okay or I need to correct my understanding of MVVM which I confess is very limited as at the moment.

I have created a simple addition application which gets two number as input and provide the added number after clicking the Button.

Please give me your honest (and brutal) opinion, since that will help me improve the most.


using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel;  namespace addition.Model {     class Number     {   public int number1             { get; set; }     public int number2         { get; set; }    public int number3         { get; set; }       } } 


using addition.Model;  using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel; using System.Collections.ObjectModel; using System.Windows; using System.Windows.Controls; using System.Windows.Input;   namespace addition.ViewModel {     class ViewModel : INotifyPropertyChanged     {         private Number n1 = new Number();         int num, num1;           public RelayCommand AddNew { get; set; }         private string _number1;  public string FirstArgument {      get { return this._number1; }     set     {         this._number1 = value;         if (int.TryParse(_number1.ToString(), out num))         {             this.n1.number1 = num;             this.OnPropertyChanged("FirstArgument");          }         else { MessageBox.Show("The given Value is not a Number "); }      } } private string _number2;          public string secondargument         {             get { return this._number2; }              set             {                 this._number2 = value;                 if (int.TryParse(_number2.ToString(), out num1))                 {                     this.n1.number2 = num1;                     this.OnPropertyChanged("secondargument");                 }                 else { MessageBox.Show("The given Value is not a Number "); }              }         }          private string _number3;          public string Addedargument         {             get { return this._number3; }             set             {                 this._number3 = value;                 this.OnPropertyChanged("Addedargument");             }         }          public  ViewModel()     {          AddNew = new RelayCommand(o => AddNumbers());      }       private void AddNumbers()     {         var a = this.FirstArgument;         var b = this.secondargument ;     var c = (Convert.ToInt32(a) + Convert.ToInt32(b)).ToString();     MessageBox.Show(c);     Addedargument = c;       }      #region INotifyPropertyChanged Members      public event PropertyChangedEventHandler PropertyChanged;     private void OnPropertyChanged(string propertyName)     {         if (PropertyChanged != null)         {             PropertyChanged(this, new PropertyChangedEventArgs(propertyName));         }     }     #endregion      } } 


<Window x:Class="addition.Window1"          xmlns:vm="clr-namespace:addition.ViewModel"      xmlns=""     xmlns:x=""     Title="Window1" Height="300" Width="300">     <Window.DataContext>         <vm:ViewModel />     </Window.DataContext>     <Grid>          <Label Height="28" Margin="28,54,0,0" Name="Number1" VerticalAlignment="Top" HorizontalAlignment="Left" Width="48">Number</Label>         <TextBox Height="28" Margin="112,56,46,0"  Text ="{Binding Path = FirstArgument}"   Name="textBox1" VerticalAlignment="Top" />         <Label Margin="28,106,0,128" Name="Number2" Width="58" HorizontalAlignment="Left">Number1</Label>         <TextBox Height="28" Margin="112,120,46,120" Text ="{Binding  Path = secondargument}" Name="textBox2" />         <Label Height="28" Margin="28,0,0,75" Name="label1" VerticalAlignment="Bottom" HorizontalAlignment="Left" Width="58">Number2</Label>         <TextBox Height="23" Margin="112,0,46,68" Name="textBox3" Text="{Binding Path = Addedargument}" VerticalAlignment="Bottom" />         <Button Height="23"  HorizontalAlignment="Left" Margin="39,0,0,16" Name="button1" VerticalAlignment="Bottom" Width="75" Command="{Binding AddNew}">Button</Button>     </Grid> </Window> 

When to use The Messenger (Mediator) Pattern in MVVM design

I got confused with the role of the Messenger in MVVM. I see contradictory articles about it.

This Article by MSDN by:

Communicating from the View-Model to the View
Observant readers will notice that Figure 1 has one arrow missing: in this figure, there is no way for the View-Model to communicate with the view. As mentioned earlier, the View-Model should ideally have no knowledge of the view that it is attached to. In fact, it is very common for a given View-Model to be attached to multiple views—for instance, because one view might become too complex and be split into two pages. To guarantee flexibility, the View-Model must have only an abstracted knowledge of what the view can do.
There are multiple ways to solve this issue. The two solutions that I propose here are using MVVM Light’s Messenger class and using view services.

generally saying that the messages should be from the View-Model to the View in case needed.

Also in this article, it warns about using the Messenger widely as it causes code to be less readable (which I agree with).

But on Another Article
It’s used differently to communicate messages between View-Models

UML Diagram showing Messenger communication between View-Models

In this scenario, I don’t get the “Why VM cant have reference to another VM?”
as the referenced View-Model can easily be mocked and tested.