L
L
Ledington2021-11-01 13:28:44
WPF
Ledington, 2021-11-01 13:28:44

How to bind ObservableCollection and INotifyCollectionChanged?

There is an Employee: ViewModel class that is displayed in the MainViewModel : ViewModel class when data is entered.
I also created the Tree class: INotifyCollectionChanged, but I still can’t figure out how to attach it to the rest.
Can you please tell me how can I bind ObservableCollection and INotifyCollectionChanged so that it is displayed in WPF?
Perhaps you need to add something else to the XAML ...

Employee:ViewModel
internal class Employee: ViewModel
{
    public string Name { get; set; }

    public int Salary { get; set; }

    public string Display { get { return Name + " - " + Salary; } }
}


Tree : INotifyCollectionChanged
public class Tree : INotifyCollectionChanged
{
    Node _root = null; 

    public event NotifyCollectionChangedEventHandler CollectionChanged;

    public void Add(string name, int pay) 
    {
        Node current = new Node();
        current.Name = name; 
        current.Salary = pay;     
        if (_root != null) 
        {
            _root.Add(current.Name, current.Salary);
        }
        else 
        {
            _root = current;
        }

        CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add));
    }

... и т.д.


MainViewModel : ViewModel
internal class MainViewModel : ViewModel
{
    public MainViewModel()
    {
        Employees = new ObservableCollection<Employee>();
    }

    public ICommand AddEmployeeCommand { get { return new Command(AddEmployee); } }
    public ObservableCollection<Employee> Employees { get; private set; }
    public string Name { get; set; }
    public int Salary { get; set; }

    private void AddEmployee()
    {
        var employee = new Employee() { Name = this.Name, Salary = this.Salary };
        Employees.Add(employee);

        Name = null;
        Salary = 0;
        RaisePropertyChanged(() => Name);
        RaisePropertyChanged(() => Salary);
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2021-11-04
@Ksarrik

In your case, displaying the Employee list is as simple as binding the ObservableCollection to a WPF list item. ObservableCollection already implements the INotifyCollectionChanged and NotifyPropertyChanged interfaces, so no additional binding is required https:// docs.microsoft.com/en-us/dotnet/api/system.collect...
ObservableCollection can be used in its pure form
If the properties of the Employee class in the interface were updated, then you need to implement the NotifyPropertyChanged interface in the Employee class.
In your case, to bind the ViewModel to WPF, it is enough to bind the collection to lists:

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800" Loaded="Window_Loaded" >
    <Grid>
        <ListBox x:Name="listbox1" DisplayMemberPath="Name">
            </ListBox>
    </Grid>
</Window>

public partial class MainWindow : Window
    {
        private MainViewModel viewModel = new MainViewModel();


        public MainWindow()
        {
            InitializeComponent();
            //добавляем сотрудников
            viewModel.Employees.Add(new Employee() {Name="Иванов Иван" });
            viewModel.Employees.Add(new Employee() { Name = "Петров Петр" });
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            //привязываем viewModel (необязательно для отображения списка)
            this.DataContext = viewModel;

            //привязываем коллекцию
            this.listbox1.ItemsSource = viewModel.Employees;
        }
    }

61838d6849b9a243115942.png
The Tree class, if the necessary interfaces are implemented, can be used instead of the ObservableCollection class.
More details can be found here https://metanit.com/sharp/wpf/22.2.php

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question