wpf 实现增删改查demo

当然,这里是一个简单的WPF示例,展示如何实现一个具有列表查询、增加、删除和修改功能的应用程序。这个示例使用MVVM模式,绑定一个简单的User对象列表。

 项目结构

1. Model: User
2. ViewModel: MainViewModel
3. View: MainWindow.xaml

 1. Model

首先,定义一个简单的User模型。

csharp
using System.ComponentModel;

namespace WpfAppDemo
{
    public class User : INotifyPropertyChanged
    {
        private int _id;
        private string _name;

        public int Id
        {
            get { return _id; }
            set
            {
                _id = value;
                OnPropertyChanged(nameof(Id));
            }
        }

        public string Name
        {
            get { return _name; }
            set
            {
                _name = value;
                OnPropertyChanged(nameof(Name));
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}


 2. ViewModel

定义MainViewModel,它包含用户列表和用于增删改操作的命令。

csharp
using System.Collections.ObjectModel;
using System.Windows.Input;

namespace WpfAppDemo
{
    public class MainViewModel : INotifyPropertyChanged
    {
        private User _selectedUser;
        private string _newUserName;
        private int _nextId = 1;

        public ObservableCollection<User> Users { get; set; }

        public User SelectedUser
        {
            get { return _selectedUser; }
            set
            {
                _selectedUser = value;
                OnPropertyChanged(nameof(SelectedUser));
            }
        }

        public string NewUserName
        {
            get { return _newUserName; }
            set
            {
                _newUserName = value;
                OnPropertyChanged(nameof(NewUserName));
            }
        }

        public ICommand AddUserCommand { get; }
        public ICommand DeleteUserCommand { get; }
        public ICommand UpdateUserCommand { get; }

        public MainViewModel()
        {
            Users = new ObservableCollection<User>();
            AddUserCommand = new RelayCommand(AddUser);
            DeleteUserCommand = new RelayCommand(DeleteUser, CanDeleteOrUpdateUser);
            UpdateUserCommand = new RelayCommand(UpdateUser, CanDeleteOrUpdateUser);
        }

        private void AddUser(object parameter)
        {
            Users.Add(new User { Id = _nextId++, Name = NewUserName });
            NewUserName = string.Empty;
        }

        private void DeleteUser(object parameter)
        {
            if (SelectedUser != null)
            {
                Users.Remove(SelectedUser);
            }
        }

        private void UpdateUser(object parameter)
        {
            if (SelectedUser != null)
            {
                SelectedUser.Name = NewUserName;
            }
        }

        private bool CanDeleteOrUpdateUser(object parameter)
        {
            return SelectedUser != null;
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}


 RelayCommand

为了实现命令,我们需要一个简单的RelayCommand实现。

csharp
using System;
using System.Windows.Input;

namespace WpfAppDemo
{
    public class RelayCommand : ICommand
    {
        private readonly Action<object> execute;
        private readonly Func<object, bool> canExecute;

        public RelayCommand(Action<object> execute, Func<object, bool> canExecute = null)
        {
            this.execute = execute ?? throw new ArgumentNullException(nameof(execute));
            this.canExecute = canExecute;
        }

        public bool CanExecute(object parameter)
        {
            return canExecute == null || canExecute(parameter);
        }

        public void Execute(object parameter)
        {
            execute(parameter);
        }

        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }
    }
}


 3. View

最后,定义XAML视图MainWindow.xaml。

xml
<Window x:Class="WpfAppDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
        <local:MainViewModel />
    </Window.DataContext>
    <Grid Margin="10">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="" />
            <ColumnDefinition Width="Auto" />
        </Grid.ColumnDefinitions>

        <TextBox Grid.Row="0" Grid.Column="0" Text="{Binding NewUserName, UpdateSourceTrigger=PropertyChanged}" Width="200" Margin="0,0,10,0" />
        <Button Grid.Row="0" Grid.Column="1" Content="Add" Command="{Binding AddUserCommand}" Width="75" />

        <ListBox Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2" ItemsSource="{Binding Users}" SelectedItem="{Binding SelectedUser}" DisplayMemberPath="Name" />

        <StackPanel Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="2" Orientation="Horizontal" HorizontalAlignment="Right">
            <Button Content="Update" Command="{Binding UpdateUserCommand}" Width="75" Margin="0,0,10,0" />
            <Button Content="Delete" Command="{Binding DeleteUserCommand}" Width="75" />
        </StackPanel>
    </Grid>
</Window>


 4. MainWindow.xaml.cs

确保在MainWindow.xaml.cs中设置DataContext。

csharp
using System.Windows;

namespace WpfAppDemo
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            DataContext = new MainViewModel();
        }
    }
}


 5. 启动应用

确保在App.xaml.cs中启动应用。

csharp
using System.Windows;

namespace WpfAppDemo
{
    public partial class App : Application
    {
    }
}


这样,你就完成了一个简单的WPF应用程序,具有列表查询、增加、删除和修改的功能。这个示例使用MVVM模式,可以帮助你理解如何在实际项目中组织代码。

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值