Reputation: 7758
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);
}
}
Upvotes: 2
Views: 2922
Reputation: 7573
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...
Upvotes: 1
Reputation: 23935
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
Upvotes: 3