C# 添加到数据库时遇到问题
所以我现在有一个Datagrid,当Datagrid中的注释被选中时,它会填充文本框字段。那部分完全有效。我想实现一个“AddNewNote按钮”。我目前的问题是,如果一个项目从未被选中,我会得到一个空引用。如果在按下按钮之前选择了一个项目,它会工作!但我需要它在两种情况下都能工作C# 添加到数据库时遇到问题,c#,wpf,C#,Wpf,所以我现在有一个Datagrid,当Datagrid中的注释被选中时,它会填充文本框字段。那部分完全有效。我想实现一个“AddNewNote按钮”。我目前的问题是,如果一个项目从未被选中,我会得到一个空引用。如果在按下按钮之前选择了一个项目,它会工作!但我需要它在两种情况下都能工作 private NoteDTO selectedNote; public NoteDTO SelectedNote { get { return this.selectedNote; } set
private NoteDTO selectedNote;
public NoteDTO SelectedNote
{
get { return this.selectedNote; }
set
{
if (this.selectedNote == value)
return;
this.selectedNote = value;
this.OnPropertyChanged("SelectedNote");
}
}
xaml侧
<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");
}
public void AddNewNote()
{
var newNote=newNote();
newNote.Person\u Id=PersonId;
newNote.Comments=SelectedNote.Comments;
newNote.Subject=SelectedNote.Subject;
使用(var ctx=DB.Get())
{
ctx.Notes.Add(新注释);
ctx.SaveChanges();
}
本条关于不动产变更(“新票据”);
}
您正试图绑定到SelectedNote
上的属性,这会在为null时导致异常:
<TextBox Text="{Binding SelectedNote.Subject}" />
<toolkit:RichTextBox Text="{Binding SelectedNote.Comments, ... }" />
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");
}