2

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

0

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

God dammit, I spent several hours to solve this stupid "Mode=TwoWay" thx,
It happens to the best of us.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.