0

我的 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"); }
        }
4

1 回答 1

0

要添加/删除,请确保 CanUserAddRows 和 CanUserDeleteRows 属性设置为 true。然后,用户应该能够通过输入底部的空白行来添加行,并通过选择行并按键盘上的 Delete 来删除行。

To edit rows, the IsReadOnly property must be false (which it is by default).

于 2012-08-01T10:37:40.943 回答