Hello, I can not figure out the addition of an object in the Model.

namespace SnakeGame.Model { [DataContract] public class DataModel { [DataMember] public List<Player> Players { get; set; } public static string DataPath = "score.dat"; public DataModel() { Players = new List<Player>() { new Player() {Score = 133, Name = "Ivan", Number = 6, Status = Player.ScoreStatus.Use} }; } public static DataModel Load() { if (File.Exists(DataPath)) return DataSerializer.DeserializeItem(DataPath); return new DataModel(); } public void Save() { DataSerializer.SerializeData(DataPath,this); } } } 

Next on the button is adding a new player, I do so.

  public partial class AddUserControll : UserControl { [DataMember] public IEnumerable<Player> Players { get; set; } public static DataModel _model; public static DataViewModel _viewModel; public static string namePlayer; private int count = 5; public AddUserControll() { InitializeComponent(); } private void button_Click(object sender, RoutedEventArgs e) { namePlayer = name.Text; var tmp = new Player() { Score = 0, Name = namePlayer, Number = count, Status = Player.ScoreStatus.Use }; _model.Players.Add(tmp); count++; try { _model = Mapper.Map<DataViewModel, DataModel>(_viewModel); _model.Save(); } catch (Exception) { } } } 

System.NullReferenceException gets out

By MVVM, everything should be correct, all View inherited by ViewModelBase: INotifyPropertyChanged

  • And what is [DataMember] ? Do you use some kind of framework? - VladD
  • [DataMember] is used for serialization, it lies in System.Runtime.Serialization; - Aleksey Bichuk
  • one
    Let us suppose. And why do you suddenly View knows about the model (in button_Click is in DataModel _model )? This is not MVVM-ovski. - VladD
  • Well, in what line do you have a NullReferenceException ? Show call stack. - VladD
  • one
    @AlekseyBichuk I quickly drafted a project in my own time, for an example, look, please, there’s nothing complicated about one window, one ViewModel and the simplest collection of objects. Hopefully something will help you ... link - Bulson

0