在 WinUI/WPF 应用程序中更改对象时自动更新数据库

问题描述 投票:0回答:1

我有一个名为 Clients 的 ObservableCollection,其中包含一个客户端列表,然后显示在 ListView 中。目前,每当添加新客户端时,列表视图都会自动更新,这很棒。然而,它也没有将客户端添加到数据库中,这正是我希望发生的情况。

目前我调用“ClientData.AddClientData(client);”在 createClientBtn_Click 函数中将其添加到数据库中,但我希望它以绑定的方式自动发生,就像更新 UI 一样。

如何在 ObservableCollection 更改时触发数据库更改?

型号

public class Order
{
    public int Id { get; set; }
    public float Amount { get; set; }
    public DateTime Date { get; set; }
    public Client Client {get; set;}
}

public class Client
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

查看型号:

public class ViewModelBase : ObservableObject {}

public partial class ClientViewModel : ViewModelBase
{
     public ObservableCollection<Client> Clients { get; set; }        
     public ClientViewModel() {}
}

public partial class OrderViewModel: ViewModelBase
{
    public ObservableCollection<Order> Orders { get; set; }
    public OrderViewModel()  {}
}

查看: 主窗口.xaml

<StackPanel x:Name="selectClientsPanel" HorizontalAlignment="Center">
    <ListView x:Name="clientsList" BorderThickness="1" Width="350" Height="Auto" HorizontalAlignment="Left"
   ItemsSource="{Binding Path=Clients, Mode=TwoWay}">
        <ListView.ItemTemplate>
            <DataTemplate x:DataType= "model:Client">
                <TextBlock Text="{x:Bind FirstName}" x:Phase="1" Margin="0,5,0,5"/>
                <TextBlock Text="{x:Bind LastName}" x:Phase="1" Margin="0,5,0,5"/>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView> 
    <StackPanel Margin="30">
                <TextBox x:Name="firstNameBox" Header="Enter first name:" PlaceholderText="First Name" />
                <TextBox Name="lastNameBoxBox" Width="250" Margin="0,0,8,0"
  Header="Enter last name:" PlaceholderText="Last Name"/>
                
                <Button x:Name="createClientBtn" Click="createClientBtn_Click">Create Client</Button>
            </StackPanel>   
</StackPanel>

MainWindow.xaml.cs:


public sealed partial class MainWindow : Window
{
    public ClientViewModel ViewModel { get; }
    public MainWindow()
    {
        this.InitializeComponent();
        ViewModel = App.GetService<ClientViewModel>();
        clientsList.ItemsSource = ViewModel.Clients;
    }

     private void createClientBtn_Click(Object sender, RoutedEventArgs e)
     {         
        if (firstNameBox.Text.Length > 0 && lastNameBox.Text.Length)
        {
           Client client=new User(firstNameBox.Text, lastNameBox.Text);
           ViewModel.Clients.Add(client);
           ClientData.AddClientData(client); //I want to call this automatically somehow
        }
     }
}

数据库相关代码:

public class DataContext : DbContext
{
     public DbSet<Client> Clients { get; set; }
     public DbSet<Order> Orders { get; set; }
}

public static class ClientData
{
     public static void AddClientData(Client client)
     {
         using (var db = new CaseNoteManagerContext())
         {
             db.Add(client);
             db.SaveChanges();
         }
     }

    public static List<Client> GetClients()
    {
        using (var db = new DataContext())
        {        
            return db.Clients.ToList();
        }
    }
}

public static class OrderData
{
     public static void AddOrderData(Order order)
     {
         using (var db = new DataContext())
         {
             db.Add(order);
             db.SaveChanges();
         }
     }
}
c# xaml mvvm data-binding community-toolkit-mvvm
1个回答
0
投票

您可以使用

ObservableCollection
CollectionChanged
事件:

Clients.CollectionChanged += Clients_CollectionChanged;
private void Clients_CollectionChanged(object? sender, NotifyCollectionChangedEventArgs e)
{
    if (e.Action is NotifyCollectionChangedAction.Add)
    {
        // Add client to the database.
        return;
    }

    if (e.Action is NotifyCollectionChangedAction.Remove)
    {
        // Remove client from the database.
        return;
    }

    // etc...
}
© www.soinside.com 2019 - 2024. All rights reserved.