Reputation: 2153
So I currently have a Datagrid, When the notes in the Datagrid are selected, It populates the Textbox Fields. That part works completely. I want to implement an "AddNewNote Button" the issue I currently have is that if an item was never selected, I get a nullreference. If an item was selected before hitting the button it works! But I need it to work in both scenarios.
private NoteDTO selectedNote;
public NoteDTO SelectedNote
{
get { return this.selectedNote; }
set
{
if (this.selectedNote == value)
return;
this.selectedNote = value;
this.OnPropertyChanged("SelectedNote");
}
}
xaml side
<DataGrid ItemsSource="{Binding Notes}" SelectedItem="{Binding SelectedNote}" />
<TextBox Text="{Binding SelectedNote.Subject}" />
<toolkit:RichTextBox Text="{Binding SelectedNote.Comments, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
public void AddNewNote()
{
var newNote = new Note();
newNote.Person_Id = PersonId;
newNote.Comments = SelectedNote.Comments;
newNote.Subject = SelectedNote.Subject;
using (var ctx = DB.Get())
{
ctx.Notes.Add(newNote);
ctx.SaveChanges();
}
this.OnPropertyChanged("newNote");
}
Upvotes: 0
Views: 57
Reputation: 66449
You're trying to bind to properties on SelectedNote
, which is causes the exception when it's null
:
<TextBox Text="{Binding SelectedNote.Subject}" />
<toolkit:RichTextBox Text="{Binding SelectedNote.Comments, ... }" />
You could handle this in the getter/setter, making sure that SelectedNote
is never null
:
get { return this.selectedNote ?? (this.selectedNote = new NoteDTO()); }
set
{
if (this.selectedNote == value)
return;
this.selectedNote = value ?? new NoteDTO(); // make sure it's never `null`
this.OnPropertyChanged("SelectedNote");
}
Upvotes: 1