I have a problem updating the layout of my listbox using MVVM with Prism 4.0.
I have no problem displaying my observablecollection to my listbox, but when I bind it to the DelegateCommand to add a new user or update a selected listbox item, it doesn’t update but the underlying object is being updated. I tried using MessageBox.Show to give me the recent output and it did the changes, but in the view.xaml it doesn’t update.
public class ProfileViewModel : DependencyObject
{
public DelegateCommand SaveCommand { get; set; }
public ObservableCollection<Persons> Persons { get; set; }
public ProfileViewModel()
{
CreatePerson();
SaveCommand = new DelegateCommand(Save,CanSave);
}
private void Save()
{
Person[0].LastUpdated = DateTime.Now
Persons.Add(new Persons { FIrstName = "Bob", LastName "Bob," LastUpdated=DateTime.Now});
}
private bool CanSave()
{
return true;
}
public void CreatePerson()
{
this.Persons = new ObservableCollection<Persons>();
Persons.Add(new Persons { FirstName = "John", LastName = "Doe", LastUpdated = DateTime.Now});Persons.Add(new Persons { FirstName = "John", LastName = "Doe", LastUpdated = DateTime.Now});
Persons.Add(new Persons { FirstName = "John", LastName = "Doe", LastUpdated = DateTime.Now});
}
}
}
ProfilePage.Xaml
<ListBox ItemsSource="{Binding Persons}" Name="ListBoxItem">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding FirstName}"/>
<TextBlock Text="{Binding LastName}" />
<Button Content="_Save" Command={Binding Source={Static Resource ProfileViewModel{, Path=SaveCommand}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
ProflilePage.xaml.cs
public partial class ProfilePage : Window
{
private ProfileViewModel _vm;
[Dependency]
public ProfileViewModel VM
{
set { _vm = value; this.DataContext = _vm; }
}
public ProfilePage()
{
InitializeComponent();
}
App.xaml.cs
protected override void OnStartup(StartupEventArgs e)
{
IUnityContainer container = new UnityContainer();
ProfileViewModel source = new ProfileViewModel();
ProfilePage window = container.Resolve<ProfilePage>();
window.show();
}
My Persons class implements the INotifyPropertyChanged and has a getter setter of LastName,FirstName and LastUpdated.
I am pretty sure you need the DataContextProxy to make bindings working. The ElementName binding will also work on ListBox