views:

199

answers:

2

I have a form that binds to an ViewModel (MVVM). Inside the form I have an ItemsControl that is bound to an element called projects in my DataContext.

When I do a save using a command pattern I save the item and do a retrieve then I want to rebind the ItemsControl to the Projects collection. This part doesn't seem to be working, all my service calls work as expected but my view is not rebound to the new collection with the added item even though it gets returned from the server.

Any help with this would really be appreciated.

XAML

<ItemsControl Name="ProjectGrid" 
      Background="Transparent" ItemsSource="{Binding Path=Projects}" Margin="0,0,0,0" VerticalAlignment="Top"
      ItemContainerStyle="{StaticResource alternatingWithTriggers}" 
      AlternationCount="2" 
      ItemTemplate="{StaticResource ItemTemplate}"/>

ViewModel

    public ICommand SaveCommand
    {
        get
        {
            if (_cmdSave == null)
            {
                _cmdSave = new RelayCommand(Save, CanSave);
            }

            return _cmdSave;
        }
    }

    public void Save()
    {
         MyService.Save();
         PopulateModel();
    }

    private void PopulateModel()
    {
        Projects = MyService.GetProjects();
    }

    public ProjectDto[] Projects
    {
        get { return _projects; }
        set
        {
            if (_projects == value)
                return;

            _projects = value;

            Notify(PropertyChanged, o => Projects);
        }
    }
+3  A: 

Make sure your ViewModel is implementing INotifyPropertyChanged. Your ui wont know about the change if your view model doesnt inform it when the property changes

use a debug converter to ascertain if your binding is failing. there is an example here of how to do this. This is a technique every wpf developer needs.

im pretty sure its your NotifyPropertyChanged that is failing, the debug converter will tell you for certain

Aran Mulholland
+1 for the debug converter link, thats some good stuff (tm)
Mike B
every project, first item - debug converter
Aran Mulholland
+1  A: 

As Aran Mulholland already said, implement INotifyPropertyChanged in your ViewModel. Also, try to use an ObservableCollection for your collections.
And instead of resetting the collection, try to use

Projects.Clear();
MyService.GetProjects().ToList().ForEach(Projects.Add);

And just as a tip, try to make the GetProjects() method async, so it won't block the UI...

Roel
Observable collection done the trick thanks Roel
Burt