Search code examples
c#wpfdatagridwpfdatagrid

How can i get the values of the list bounded to a datagrid


I have bound a list to a DataGrid. After modifying the list in the DataGrid I'd like to save the list in a xml file. how can I get access to the list in the c# code? In other words I wanna get the content of Welle1 after clicking on a Button.


InitializeComponent();

List<Wellenelement> we1 = new List<Wellenelement>();
Welle Welle1 = new Welle
            {
                Elemente = we1
            };

dataGrid.DataContext = Welle1;

```c#

Solution

  • So, first of all, using WPF, you'll have to make use of Properties and the PropertyChangedEvent.

    Go to your MainWindow.xaml.cs (or to your ViewModel, if you already use MVVM) and add beneath your Constructor (usually public MainWindow(){ //[...] )

    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged(string propertyName)
    {
      if (PropertyChanged != null)
      {
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
      }
    }
    

    you'll also have to add using System.ComponentModel; to your usings to find the required classes.

    Next you add a new Property right above your Constructor like this:

      private ObservableCollection<WellenElement> m_WellenListe;
      public ObservableCollection<WellenElement> WellenListe
        {
          get { return m_WellenListe; }
          set
          {
            m_WellenListe = value;
            OnPropertyChanged("WellenListe");
          }
        }
    

    Note: I'll suggest using an ObservableCollection over a List, if you want to change your ItemsSource at runtime. (You have to add using System.Collections.ObjectModel; to get the class)

    Now you can bind your DataGrid to your ObservableCollection:

    <DataGrid ItemsSource="{Binding WellenListe}"/>
    

    Now you can do whatever you want with your List in code behind like:

    button1_click(object sender, RoutedEventArgs e)
    {
        foreach(WellenElement welle in WellenListe)
        {
          //Save to xml
        }
    
    }