private ObservableCollection<ProjectItem> _projectItems;
public ObservableCollection<ProjectItem> DataItems
{
get { return _projectItems; }
}
public ProjectsPanelViewViewModel()
{
_projectItems = new ObservableCollection<ProjectItem>();
_createProjectCommand = new DelegateCommand(OnCreateProjectCommand);
_saveProjectCommand = new DelegateCommand(OnSaveProjectCommand);
}
private void OnCreateProjectCommand()
{
_addProjectViewModel = new AddProjectViewModel();
AddProjectView view = new AddProjectView();
view.Show();
}
private void OnSaveProjectCommand()
{
ProjectItemViewModel _vm = new ProjectItemViewModel();
_vm.ProjectName = ProjectName;
_vm.ProjectDescription = ProjectDescription;
var item = new ProjectItem(_vm);
_projectItems.Add(item);
}
XAML
<UserControl.DataContext>
<VM:ProjectsPanelViewViewModel/>
</UserControl.DataContext>
<StackPanel Name="ProjectsPanel" Style="{DynamicResource FullLengthPanelStyle}" >
<StackPanel Name="ProjectsHeader" Orientation="Horizontal" Margin="0,0,0,5">
<Label Style="{StaticResource TitleLabelStyleBlue}">projects</Label>
<Button Name="AddProjects" Margin="10,5,0,0" Style="{StaticResource CircularGreyButtonStyle}" Content="+" ToolTip="Add a new project" Command="{Binding CreateProjectCommand}"/>
<Button Name="ExpandProjects" Margin="10,5,0,0" Style="{StaticResource CircularGreyButtonStyle}" Content=">" ToolTip="Expand projects"/>
</StackPanel>
<ScrollViewer VerticalScrollBarVisibility="Visible">
<ItemsControl ItemsSource="{Binding DataItems}"/>
</ScrollViewer>
</StackPanel>
When the OnCreateProjectCommand Opens it creates a window with 2 string fields, this then has a button that executes the OnSaveProjectCommand. The commands are executed fine, however the UI does not pick up that the new item has been added to the collection. (When debugging it is in there). If however you change the code from the OnSaveProjectCommand and put it into the OnCreateProjectCommand, and hardcode the simple string values, the UI is updated correctly from the observable collection.
Can anyone give me some guidance as to why this is not working, and also the correct way that I should be spawning up a new window from this command. Should this be done with State Based view navigation from prism? We are already using this for modularisation and commanding.
Thanks for the advice.
I think you might have a reference problem there. How do you glue this ViewModels with each other? I’m not familiar with Prism, but it might happen that the VM instance you are viewing on screen is not the same as the one you’re debugging. Otherwise it doesn’t make sense. Observablecollections usually work just fine, unless you’re manipulating them from different threads other than the UI thread. Try using Snoop to spy into the running application to see what your DataContexts are.