📜  c# crud observablecollection -mvvm - C# (1)

📅  最后修改于: 2023-12-03 15:13:48.693000             🧑  作者: Mango

C# CRUD ObservableCollection with MVVM

If you are a C# developer looking to implement CRUD operations with an ObservableCollection in an MVVM architecture, then you are in the right place! In this guide, we will cover all the necessary steps to create a basic MVVM project and implement CRUD operations using an ObservableCollection in C#.

Prerequisites
  • Visual Studio or Visual Studio Code (with appropriate C# extensions)
  • Knowledge of fundamentals of C# and MVVM architecture
  • Understanding of ObservableCollection and how it differs from other collection types
Step 1: Create a new project

First, let's create a new project in Visual Studio.

  1. Open Visual Studio and select "Create a new project."
  2. Select "WPF App (.NET Framework)" under the "Windows Classic Desktop" category.
  3. Give your project a name and choose a save location.
  4. Click "Create."
Step 2: Set up MVVM architecture

Now that we have created a new project, we need to organize our code according to the MVVM architecture.

  1. Right-click on the project in Solution Explorer and select "Add -> New Folder." Name the folder "ViewModels."
  2. Right-click on the project in Solution Explorer and select "Add -> New Folder." Name the folder "Models."
  3. Right-click on the project in Solution Explorer and select "Add -> New Folder." Name the folder "Views."
Step 3: Create a model class

We will start by creating a simple model class to represent our data.

  1. Right-click on the "Models" folder and select "Add -> Class." Name the class "Person.cs".
  2. Copy and paste the following code into the Person.cs file:
public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}
Step 4: Create a view model class

Our view model class will implement the logic for our CRUD operations using an ObservableCollection of Person objects.

  1. Right-click on the "ViewModels" folder and select "Add -> Class." Name the class "MainViewModel.cs".
  2. Copy and paste the following code into the MainViewModel.cs file:
public class MainViewModel : INotifyPropertyChanged
{
    private ObservableCollection<Person> people;

    public ObservableCollection<Person> People
    {
        get { return people; }
        set
        {
            people = value;
            RaisePropertyChanged("People");
        }
    }

    public MainViewModel()
    {
        People = new ObservableCollection<Person>();
    }

    public void AddPerson(Person person)
    {
        People.Add(person);
    }

    public void UpdatePerson(Person person)
    {
        // Find the person in the collection and update their properties
        int index = People.IndexOf(person);
        if (index != -1)
        {
            People[index] = person;
        }
    }

    public void DeletePerson(Person person)
    {
        People.Remove(person);
    }

    #region INotifyPropertyChanged implementation

    public event PropertyChangedEventHandler PropertyChanged;

    private void RaisePropertyChanged(string property)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
    }

    #endregion
}
Step 5: Create a view (GUI)

Finally, let's create a view to display our data and allow users to perform CRUD operations.

  1. Right-click on the "Views" folder and select "Add -> Window." Name the window "MainWindow.xaml".
  2. Open the MainWindow.xaml file and delete all the existing XAML code.
  3. Copy and paste the following XAML code into the MainWindow.xaml file:
<Window x:Class="MyNamespace.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:MyNamespace"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
     
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <!-- Add / Update Form -->
        <GroupBox Header="Add / Update Person" Grid.Row="0">
            <Grid>
                
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto"/>
                    <RowDefinition Height="Auto"/>
                    <RowDefinition Height="Auto"/>
                </Grid.RowDefinitions>

                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto"/>
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>

                <Label Grid.Row="0" Grid.Column="0" Content="First Name:"/>
                <TextBox Grid.Row="0" Grid.Column="1" Text="{Binding SelectedPerson.FirstName, UpdateSourceTrigger=PropertyChanged}"/>

                <Label Grid.Row="1" Grid.Column="0" Content="Last Name:"/>
                <TextBox Grid.Row="1" Grid.Column="1" Text="{Binding SelectedPerson.LastName, UpdateSourceTrigger=PropertyChanged}"/>

                <Label Grid.Row="2" Grid.Column="0" Content="Age:"/>
                <TextBox Grid.Row="2" Grid.Column="1" Text="{Binding SelectedPerson.Age, UpdateSourceTrigger=PropertyChanged}"/>

                <Button Grid.Row="3" Grid.ColumnSpan="2" Content="Save" Command="{Binding SaveCommand}"/>
            </Grid>
        </GroupBox>

        <!-- Data Grid -->
        <DataGrid ItemsSource="{Binding People}" Grid.Row="1" SelectedItem="{Binding SelectedPerson}" AutoGenerateColumns="False">
            <DataGrid.Columns>
                <DataGridTextColumn Header="First Name" Binding="{Binding FirstName}"/>
                <DataGridTextColumn Header="Last Name" Binding="{Binding LastName}"/>
                <DataGridTextColumn Header="Age" Binding="{Binding Age}"/>
            </DataGrid.Columns>
        </DataGrid>

        <!-- Delete Button -->
        <Button Grid.Row="1" Content="Delete" Command="{Binding DeleteCommand}" 
                VerticalAlignment="Top" HorizontalAlignment="Right" Margin="0,5,5,0"/>
    </Grid>
</Window>
Step 6: Bind view to view model

Now, we need to bind our view to our view model class.

  1. Open the MainWindow.xaml.cs file and add the following code:
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        // Set the DataContext of the view to our view model
        DataContext = new MainViewModel();
    }
}
Step 7: Test CRUD operations

Now let's test our CRUD operations.

  1. Run the project.
  2. Click on the "Add / Update Person" section of the view and enter some data.
  3. Click the "Save" button to add the new person to the ObservableCollection.
  4. Select a person from the DataGrid and update their information in the "Add / Update Person" section.
  5. Click the "Save" button to update the selected person.
  6. Select a person from the DataGrid and click the "Delete" button to remove them from the ObservableCollection.

Congratulations! You have successfully implemented CRUD operations using an ObservableCollection in an MVVM architecture in C#.