我的 WPF 应用程序窗口中有一个数据网格,我必须将其绑定到一个可观察的集合。我必须为用户提供选项,以便能够在此数据网格中编辑、删除、添加和编辑项目。
我在下面做了数据网格的绑定,但想问我如何允许用户轻松地从数据网格中添加、编辑/更新、删除项目。
这是我当前的代码:
.xaml
<DataGrid x:Name="dgrQuestions" AutoGenerateColumns="False" Height="272" HorizontalAlignment="Left" Margin="42,73,0,0" VerticalAlignment="Top" Width="669" ItemsSource="{Binding QuestionsList}">
<DataGrid.Columns>
<DataGridTextColumn Header="FirstQues" Binding="{Binding Question}"/>
<DataGridTextColumn Header="SecondQues" Binding="{Binding Answer}"/>
<DataGridTextColumn Header="ThirdQues" Binding="{Binding Hint}"/>
</DataGrid.Columns>
</DataGrid>
.xaml.cs 代码
using Quest; //class having the format of the question
public class Master
{
private ObservableCollection<Quest> questList;
public event PropertyChangedEventHandler PropertyChanged;
public ObservableCollection<Quest> QuestionList
{
get { return questList; }
set
{
questList = value;
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("QuestionsList"));
}
}
//Add, Edit, Remove, Reset methods required
}
为其创建对象的类的.cs 代码(此处仅提及属性):
public string Question
{
get { return _question; }
set{ _question = value; OnPropertyChanged("Question"); }
}
public string Answer
{ get { return _answer; }
set {_answer = value; OnPropertyChanged("Answer"); }
}
public string Hint
{
get { return _hint; }
set { _hint = value; OnPropertyChanged("Hint"); }
}