代码改变世界

WPF开发经验

2019-04-13 19:12  .net小跟班(杜)  阅读(834)  评论(0编辑  收藏  举报

WPF是微软推出的一款新的CS编程框架,告别了Winform时代

1、创建MyPropertyChanged类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;

namespace WpfApplication2
{
    public class MyPropertyChanged : INotifyPropertyChanged
    {
        //属性改变通知事件
        public event PropertyChangedEventHandler PropertyChanged;

        //属性改变通知事件方法
        public void Notify(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}

2、创建MyCommand类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace WpfApplication2
{
    public class MyCommand : ICommand
    {
        //事件注册
        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

        bool _CanExecute;
        Action<object> _Execute;
        //按钮是否可用
        public bool CanExecute(object parameter)
        {
            return _CanExecute;
        }

        //按钮点击事件
        public void Execute(object parameter)
        {
            _Execute(parameter);
        }

        //构造函数
        public MyCommand(Action<object> execute, bool canExecute = true)
        {
            _CanExecute = canExecute;
            _Execute = execute;
        }

    }
}

3、创建数据操作MainWindowViewModel类

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace WpfApplication2
{
    public class MainWindowViewModel : MyPropertyChanged
    {
        //模型实例
        MainWindowModel _MainWindowModel;

        string _Name;
        //属性名称绑定
        public string Name
        {
            get
            {
                return _Name;
            }
            set
            {
                _Name = value;
                Notify(nameof(Name));
            }
        }

        //数据集绑定
        public ObservableCollection<MainWindowModel> UserList { get; set; }

        //查询按钮事件绑定
        public MyCommand QueryCommand { get; set; }
        //新增按钮事件
        public MyCommand AddCommand { get; set; }
        /// <summary>
        /// 删除按钮
        /// </summary>
        public MyCommand DeleteCommand { get; set; }

        ServiceReference1.Service1Client service1Client = new ServiceReference1.Service1Client();

        public MainWindowViewModel()
        {
            UserList = new ObservableCollection<MainWindowModel>();
            QueryCommand = new MyCommand(QueryStudent);
            AddCommand = new MyCommand(AddStudent);
            DeleteCommand = new MyCommand(DeleteStudent);
            GetStudentList();
        }

        private void AddStudent(object parameter)
        {
            var addwindow = new AddStudent();
            addwindow.AddStudentViewModel._UpdateUI += new AddStudentViewModel.UpdateUI(GetStudentList);
            addwindow.ShowDialog();
        }

        public void DeleteStudent(object parameter)
        {
            var r = MessageBox.Show("是否确认删除", "删除", MessageBoxButton.YesNo);
            if (r == MessageBoxResult.Yes)
            {
                int id = int.Parse(parameter.ToString());
                var result = service1Client.DeleteStuList(id);
                if (result > 0)
                {
                    MessageBox.Show("删除成功");
                }
                else
                {
                    MessageBox.Show("删除失败");
                }

                var item = UserList.Where(a => a.Id == id).FirstOrDefault();
                UserList.Remove(item);
            }

        }

        public void QueryStudent(object parameter)
        {
            GetStudentList();
        }

        public void GetStudentList()
        {
            UserList.Clear();
            var list = service1Client.GetStuList(Name).ToList();
            foreach (var item in list)
            {
                _MainWindowModel = new MainWindowModel();
                _MainWindowModel.Id = item.Id;
                _MainWindowModel.Name = item.Name;
                _MainWindowModel.Age = item.Age;
                UserList.Add(_MainWindowModel);
            }
        }
    }
}

4、在页面后台绑定操作类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApplication2
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        //视图模型实例
        MainWindowViewModel _MainWindowViewModel;
        //视图模型属性
        public MainWindowViewModel MainWindowViewModel
        {
            get
            {
                if (_MainWindowViewModel == null)
                {
                    _MainWindowViewModel = new MainWindowViewModel();
                }
                return _MainWindowViewModel;
            }
        }

        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = MainWindowViewModel;

        }

    }
}

5、在页面前台通过Command绑定事件

 <Label x:Name="label" Content="姓名:" HorizontalAlignment="Left" Margin="39,46,0,0" VerticalAlignment="Top"/>
        <TextBox x:Name="textBox" HorizontalAlignment="Left" Height="23" Margin="76,46,0,0" TextWrapping="Wrap" Text="{Binding Name,Mode=TwoWay,UpdateSourceTrigger=LostFocus}" VerticalAlignment="Top" Width="120"/>
        <Button x:Name="button" Content="查询" HorizontalAlignment="Left" Margin="239,46,0,0" VerticalAlignment="Top" Width="75" Command="{Binding QueryCommand}"/>
        <DataGrid x:Name="dataGrid" HorizontalAlignment="Left" Margin="39,76,0,0" VerticalAlignment="Top" Height="197" Width="418" ItemsSource="{Binding UserList}" AutoGenerateColumns="False" CanUserAddRows="False">
            <DataGrid.Columns>
                <!--序号-->
                <DataGridTextColumn Header="序号" Width="80" Binding="{Binding Id}"/>
                <!--视频名称-->
                <DataGridTextColumn Header="姓名" Width="100" Binding="{Binding Name}" />
                <!--文件大小-->
                <DataGridTextColumn Header="年龄" Width="120" Binding="{Binding Age}" />
                <!--操作-->
                <DataGridTemplateColumn Header="操作" MinWidth="120">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Button Content="删除"
                            Command="{Binding Path=DataContext.DeleteCommand,
                                RelativeSource= {RelativeSource FindAncestor,
                                AncestorType={x:Type DataGrid}}}"
                            CommandParameter="{Binding Id}" />
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>
        <Button x:Name="button1" Content="新增" HorizontalAlignment="Left" Margin="336,46,0,0" VerticalAlignment="Top" Width="75" Command="{Binding AddCommand}"/>

6、在App.xaml中通过StartupUri设置启动页

<Application x:Class="WpfApplication2.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:WpfApplication2"
             
             StartupUri="MainWindow.xaml">
    <Application.Resources>
         
    </Application.Resources>
</Application>

7、后续补充