Search code examples
c#wpfxamldatagrid

Bind List<object> to Datagrid WPF, C#


I'm totally new to WPF so heres my code:

 <DataGrid x:Name="dgVarConfig" ItemsSource="{Binding varConfigList, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" Margin="10,59,0,0" VerticalAlignment="Top" Height="403" Width="1278" AutoGenerateColumns="False" CanUserAddRows="False" CanUserDeleteRows="False" CanUserResizeRows="False" HeadersVisibility="Column">

            <DataGrid.Columns>
                <DataGridTextColumn  Width="auto" Header="Match Ausdruck" Binding="{Binding match_expression}"></DataGridTextColumn>
            </DataGrid.Columns>
</DataGrid>

My Files: MainWindow.xaml, MainController.cs, VarConfigDAO.cs

the varConfigDAO.cs returns the list to the MainController, and the MainController.cs returns it do MainWindows.xaml.

This is the VarConfig.cs:

 public class VarConfig
    {
        public int id { get; set; }
        public String group { get; set; }
        public String machine { get; set; }
        public String match_expression { get; set; }
        public String variant_new_1 { get; set; }
        public String calc_formula_1 { get; set; }
        public String variant_new_2 { get; set; }
        public String calc_formula_2 { get; set; }
    }

It works if i set the itemssource programmaticly:

dgVarConfig.Itemssource = mainController.loadVarConfigList();

But thats not what i want because i want to update the list via the grid (insert, delete, update lines => Mode=TwoWay)

Any clue how i can fill the itemssource via xaml?


Solution

  • Create a view model class with a property that holds a collection of VarConfig objects. The collection should notify the view about changes (like added or removed elements). An appropriate collection type would therefore be ObservableCollection:

    public class ViewModel
    {
        public ObservableCollection<VarConfig> VarConfigList { get; }
            = new ObservableCollection<VarConfig>();
    }
    

    Set the DataContext of your UI (e.g. your MainWindow) to an instance of the view model, for example in code behind in the MainWindow constructor like this:

    public MainWindow()
    {
        InitializeComponent();
    
        var viewModel = new ViewModel();
        // fill viewModel.VarConfigList
    
        DataContext = viewModel;
    }
    

    Bind to the VarConfigList property in XAML. It is not necessary to set Mode=TwoWay or UpdateSourceTrigger=PropertyChanged, as the ItemsSource property is only bound one-way (the DataGrid - or any other ItemsControl - never sets it):

    <DataGrid ItemsSource="{Binding VarConfigList}" ...>
        ...
    </DataGrid>
    

    Finally, if you also want the UI to react on changes of the individual VarConfig properties, it should implement the INotifyPropertyChanged interface:

    public class VarConfig : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
    
        private void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    
        private int id;
        public int Id
        {
            get { return id; }
            set
            {
                id = value;
                OnPropertyChanged(nameof(Id));
            }
        }
    
        // similar code for the other properties
    }
    

    Note the casing. It's widely accepted to write C# property names in PascalCase.