Jester
Jester

Reputation: 3317

WPF data grid not updating

Hi There seem to be different reasons for that and I tried a few of them but it does not seem to work.

My scenario is that: I add an item to the collection linked as a datasource to the grid and then run a command line or some other code.

The problem

The first row shows up but after that I can add rows but they don't show up in the grid.

my code:

View

    <DataGrid Margin="5" Name="progress"
        AutoGenerateColumns="False" 
        CanUserAddRows="False" 
        SelectionMode="Extended" 
        SelectionUnit="Cell" 
        Height="150"
        ItemsSource="{Binding}">
     <DataGrid.Columns>
          <DataGridTextColumn Header="" Width="370" Binding="{Binding Action}" IsReadOnly="True" />
          <DataGridTextColumn Header="" Width="100" Binding="{Binding Success}" IsReadOnly="True" />
           </DataGrid.Columns>
  </DataGrid>

Code behind

ObservableCollection<StepResult> stepResults;
stepResults = new ObservableCollection<StepResult>();
progress.DataContext = stepResults;
private void Updater_StepStart(object sender, ScriptInterpreter.Events.StepEventArguments e)
{
     stepResults.Add(new StepResult
     {
        Action = e.StepName,
        Success = true
      });
}

What I tried to so far:

progress.UpdateLayout();
progress.ItemsSource = null;
progress.ItemsSource = stepResults;

Nothing working tho :(

Upvotes: 0

Views: 302

Answers (1)

lightlike
lightlike

Reputation: 162

You should try setting the ObservableCollection as as Property and binding the ItemsSource to it. Something like this:

<DataGrid ItemsSource="{Binding stepResult}"/>

And the Code-Behind:

private ObservableCollection<StepResult> _stepResults;
public ObservableCollection<StepResult> StepResults
{
    get { return _stepResults; }
    set
    {
        if (_stepResult == value)
            return;
        _stepResults = value;
        OnPropertyChanged();
    }
}

And settings the DataContext like this:

progress.DataContext = this;

This should work. At least it almost always did for me.

Upvotes: 1

Related Questions