I made a simple example playing with MVVM. I have a simple class Person in Models, then a class PersonsViewModel has a list of Person. I'm doing so by install Prism through Nuget and raise the event PropertyChanged in the collection of people.
private ObservableCollection<Person> people;
public ObservableCollection<Person> People
{
get { return people; }
set
{
people = value;
this.RaisePropertyChanged("People");
}
}
then I bind it to a datagrid
<DataGrid Grid.Row="1" x:Name="dataGrid" AutoGenerateColumns="False" ItemsSource="{Binding People}" >
<DataGrid.Columns>
<DataGridTextColumn Header="First Name" Binding="{Binding FirstName, Mode=OneWay}"/>
<DataGridTextColumn Header="Last Name" Binding="{Binding LastName, Mode=OneWay}"/>
<!--<DataGridTextColumn Header="Sex" Binding="{Binding Sex, Mode=TwoWay}"/>-->
<DataGridComboBoxColumn Header="Sex" SelectedItemBinding="{Binding Sex, Converter={StaticResource sexTypeConverter}}" ItemsSource="{Binding Source={StaticResource sexType}}"/>
<DataGridTextColumn Header="Score" Binding="{Binding Score, Mode=TwoWay}"/>
</DataGrid.Columns>
</DataGrid>
it works find so far, i can insert or remove line, change the quantity in the UI and reflect to the viewmodel. But the problem is that if I change the quantity in the code, it won't show in the form until I double click into it. here is the screenshot when my app starts, i've added three records with different scores. enter image description here
in my code, I've put a command as below, so basically everytime I run the command it will increase the score by 20 for each person. Which it does. the problem is that after I click the button, the score on the form doesn't change, only when i double click into the field score, I can see the number is actually changed.
private void IncQty()
{
foreach (Person item in this.People)
{
item.Score += 20;
}
}
I've tried to search online, some say that I should bind the datasource again. But isn't ObservableCollection already implements the INotifyPropertyChanged and my view should talk to my viewmodel everytime something is changed? Also ideally I shouldn't do anything in my ViewModel to manipulate the element in View, it seems to break this rule if I write some code to attach the bind again in viewmodel. Please help. Thanks a lot.