Reputation: 54
I'm trying to implement MVVM patter in my app, and got problem with data binding. Everything works pretty fine, untill a new item appears in my collection binded to ListBox. ListBox is just not updating, and after I try to click on that box exceptions about ItemsControl is thrown.
MainView.xaml
<Window.DataContext>
<ViewModel:MainViewModel/>
</Window.DataContext>
<ListBox x:Name="Scripts" ItemsSource="{Binding Scripts, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" DisplayMemberPath="Name" SelectedItem="{Binding SelectedScript}"/>
MainViewModel.cs
class MainViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public List<Script> Scripts
{
get; set;
}
public RelayCommand NewScriptCommand
{
get; set;
}
public MainViewModel()
{
Scripts = Script.Scripts;
NewScriptCommand = new RelayCommand(NewScript);
}
private void NewScript()
{
Script.NewScript();
OnPropertyChanged("Scripts");
}
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
And my Model, class Script.cs
public class Script
{
private static List<Script> _scripts;
public static List<Script> Scripts
{
get
{
if(_scripts == null)
{
_scripts = GetScripts();
}
return _scripts;
}
}
public static void NewScript()
{
_scripts.Add(new Script());
}
}
I was thinking about make ObservableCollection in MainViewModel, but then occurred other problem about updating that collection when List<Script>
Scripts get new element.
Upvotes: 0
Views: 68
Reputation: 5236
Replace List with ObservableCollection and everything will start working. Not sure what "problem" you are talking about. Remove OnPropertyChanged("Scripts"). The Scripts property has not changed...the collection has changed. You need to raise a collection changed event which is what ObservableCollection does.
Upvotes: 1