RayOldProf
RayOldProf

Reputation: 1070

WPF Datagrid does not get updated

I have define a datagrid as follow:

<DataGrid Grid.Row="0" Grid.Column="0" x:Name="s" MaxHeight="300"
           ItemsSource="{Binding MsgCollection, IsAsync=False, Mode=OneTime}">
    <DataGrid.Columns>
        <DataGridTextColumn x:Name="BankId"
                            Header="Bank Nr."
                            Binding="{Binding BankId}"
                            DisplayIndex="0" />

        <DataGridTextColumn x:Name="MessageB"
                            Header="Message B"
                            Binding="{Binding MessageB}"
                            DisplayIndex="1" />

    </DataGrid.Columns>
</DataGrid>

the viewModel Code looks like this:

 public class AwesomeDataViewModel : ViewModelBase
 {
   ...
   public ObservableCollection<Bank> MsgCollection
    {
        get
        {
            return m_Msgs;
        }
        set
        {
            m_Msgs = value;
            OnPropertyChanged("MsgCollection");
        }
    }

 AwesomeRandomMethode(){
    ...
    // bankCollection contains 200 items
     MsgCollection = new ObservableCollection<Bank>(bankCollection); 
    OnPropertyChanged("MsgCollection");
 }
}

The AwesomeRandomMethode() is called later in the program to add items into the dataGrid. I notify the change by calling OnPropertyChangedbut nothing happens.

I know theOnPropertyChanged works, because i have a button that make use of it and it get notified.

However if I toggle the tab, suddenly the datagrid get updated!

Im looking for a solution that does not violate MVVM principles

Upvotes: 2

Views: 148

Answers (2)

Jose
Jose

Reputation: 1897

Change

ItemSource="{Binding MsgCollection, IsAsync=False, Mode=OneTime}"

for

ItemSource="{Binding MsgCollection, IsAsync=False, Mode=TwoWay}"

WPF binding modes: https://stackoverflow.com/a/2305234/5147720

Upvotes: 1

Matt Wilkinson
Matt Wilkinson

Reputation: 590

Your issue is your binding it should be a two way binding on the source items. A default binding is a TwoWay so just don't declare it explicitly.

<DataGrid Grid.Row="0" Grid.Column="0" x:Name="s" MaxHeight="300" ItemsSource="{Binding MsgCollection}">
</DataGrid>

You should also just have your ObservableCollection declared already and Add or Remove Items. This way everything will up date automatically.

Upvotes: 2

Related Questions