WPF+MVVM模式的小案例案例主要的目录结构

下面一步一步建立整个小程序的目录和相应的代码程序。

1、打开VS, 新建项目WPFDemo.Client.CustType(自己可以写自己的程序名称,这个自定义取决于自己)

2、在建文件夹Data,Models,OthersServices,ViewModels,Views等文件夹。

3、文件夹Data中添加CustTypeData.xml文件。内容如下:

<?xml version="1.0" encoding="utf-8" ?>
<Cust_TypeS>
  <Cust_Type>
    <CUSTTYPE_ID>104</CUSTTYPE_ID>
    <CUSTTYPE_NO></CUSTTYPE_NO>
    <CUSTTYPE_NAME>华北</CUSTTYPE_NAME>
    <REM>子区域的上级区域不显子区域的上级区域不显子区域的上级区域不显子区域的上级区域不显子;域的上级··不!</REM>
  </Cust_Type>
  <Cust_Type>
    <CUSTTYPE_ID>105</CUSTTYPE_ID>
    <CUSTTYPE_NO></CUSTTYPE_NO>
    <CUSTTYPE_NAME>华南</CUSTTYPE_NAME>
    <REM>ssdfdsdfsd</REM>
  </Cust_Type>
  <Cust_Type>
    <CUSTTYPE_ID>106</CUSTTYPE_ID>
    <CUSTTYPE_NO></CUSTTYPE_NO>
    <CUSTTYPE_NAME>华西</CUSTTYPE_NAME>
    <REM>域的上级··不!</REM>
  </Cust_Type>
  <Cust_Type>
    <CUSTTYPE_ID>111</CUSTTYPE_ID>
    <CUSTTYPE_NO></CUSTTYPE_NO>
    <CUSTTYPE_NAME>华东</CUSTTYPE_NAME>
    <REM>子区区域</REM>
  </Cust_Type>
  <Cust_Type>
    <CUSTTYPE_ID>113</CUSTTYPE_ID>
    <CUSTTYPE_NO></CUSTTYPE_NO>
    <CUSTTYPE_NAME>444</CUSTTYPE_NAME>
    <REM>444</REM>
  </Cust_Type>
</Cust_TypeS>

4、文件夹Models中添加Cust_Type.cs文件。内容如下:

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

namespace WPFDemo.Client.CustType.Models
{
    /// <summary>
    /// 客户分类
    /// </summary>
    public partial class Cust_Type
    {
        private long _CUSTTYPE_ID;
        /// <summary>
        /// ID
        /// </summary>
        public long CUSTTYPE_ID
        {
            get { return _CUSTTYPE_ID; }
            set { _CUSTTYPE_ID = value; }
        }

private string _CUSTTYPE_NO;
        /// <summary>
        /// 分类编码
        /// </summary>
        public string CUSTTYPE_NO
        {
            get { return _CUSTTYPE_NO; }
            set { _CUSTTYPE_NO = value; }
        }

private string _CUSTTYPE_NAME;
        /// <summary>
        /// 名称
        /// </summary>
        public string CUSTTYPE_NAME
        {
            get { return _CUSTTYPE_NAME; }
            set { _CUSTTYPE_NAME = value; }
        }

private string _REM;
        /// <summary>
        /// 备注
        /// </summary>
        public string REM
        {
            get { return _REM; }
            set { _REM = value; }
        }

}
}

5、文件夹Others添加OperatorEnum.cs文件。内容如下:

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

namespace WPFDemo.Client.CustType.Others
{
    /// <summary>
    /// 枚举操作数
    /// 增 Create = 1, 删 Delete=2, 改 Update=3, 查 Retrieve=4
    /// </summary>
    public enum OperatorEnum
    {
        /// <summary>
        /// 增
        /// </summary>
        Create = 1,
        /// <summary>
        /// 删
        /// </summary>
        Delete = 2,
        /// <summary>
        /// 改
        /// </summary>
        Update = 3,
        /// <summary>
        /// 查
        /// </summary>
        Retrieve = 4
    }
}

6、在Services中添加 IDataService.cs(数据读取操作接口),IDataOperatorService.cs(数据存储操作接口)文件以及相应的实现文件(可以根据相应的数据库来实现相应的接口,如:sql server,oracle数据库,xml文件等),内容如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WPFDemo.Client.CustType.Models;

namespace WPFDemo.Client.CustType.Services
{
    /// <summary>
    /// 获取数据接口
    /// </summary>
    public interface IDataService
    {
        /// <summary>
        /// 获取数据列表
        /// </summary>
        /// <returns></returns>
        List<Cust_Type> GetCustTypeList();       
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WPFDemo.Client.CustType.Others;

namespace WPFDemo.Client.CustType.Services
{
    interface IDataOperatorService
    {
        void SaveCustTypeList(List<Models.Cust_Type> custTypeList, OperatorEnum enumData);
    }
}

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using WPFDemo.Client.CustType.Models;

namespace WPFDemo.Client.CustType.Services
{
    /// <summary>
    /// 通过XML获取数据
    /// </summary>
    class XmlDataService : IDataService
    {
        public List<Cust_Type> GetCustTypeList()
        {
            string localPath = Path.Combine(Environment.CurrentDirectory, @"Data\CustTypeData.xml");
            XDocument xdoc = XDocument.Load(localPath);
            var eleList = xdoc.Descendants(nameof(Cust_Type));
            List<Cust_Type> custTypeList = new List<Cust_Type>();
            foreach (var item in eleList)
            {
                Cust_Type temp = new Cust_Type();
                long id = 0;
                temp.CUSTTYPE_ID = long.TryParse(item.Element(nameof(Cust_Type.CUSTTYPE_ID)).Value, out id) ? id : 0;
                temp.CUSTTYPE_NO = item.Element(nameof(Cust_Type.CUSTTYPE_NO)).Value;
                temp.CUSTTYPE_NAME = item.Element(nameof(Cust_Type.CUSTTYPE_NAME)).Value;
                temp.REM = item.Element(nameof(Cust_Type.REM)).Value;
                custTypeList.Add(temp);
            }
            return custTypeList;
        }

}
}

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using WPFDemo.Client.CustType.Models;
using WPFDemo.Client.CustType.Others;

namespace WPFDemo.Client.CustType.Services
{
    class XmlDataOperatorService : IDataOperatorService
    {
        public void SaveCustTypeList(List<Cust_Type> custTypeList)
        {
            //string localpath = System.IO.Path.Combine(Environment.CurrentDirectory, @"Data\xml.txt");
            //System.IO.File.AppendAllLines(localpath, custTypeList.Where(o => o.CUSTTYPE_ID != 0).Select(i => i.CUSTTYPE_NAME).ToArray());          
        }

public void SaveCustTypeList(List<Cust_Type> custTypeList, OperatorEnum enumData)
        {
            //string localPath = Path.Combine(Environment.CurrentDirectory, @"Data\Data.xml");
            string localPath = @"Data\CustTypeData.xml";
            XDocument xdoc = XDocument.Load(localPath);
            switch (enumData)
            {
                case OperatorEnum.Create:
                    this.Create(xdoc, custTypeList);
                    break;
                case OperatorEnum.Delete:
                    this.Delete(xdoc, custTypeList);
                    break;
                case OperatorEnum.Update:
                    this.Update(xdoc, custTypeList);
                    break;
                    //case OperatorEnum.Retrieve:
                    //    this.Retrieve(xdoc, custTypeList);
                    //    break;
            }
        }

public const string savePath = @"Data\CustTypeData.xml";

/// <summary>
        /// 增
        /// </summary>
        public void Create(XDocument xdoc, List<Cust_Type> custTypeList, string path = savePath)
        {
            if (xdoc == null || custTypeList == null || custTypeList.Count <= 0)
                return;
            foreach (var item in custTypeList)
            {
                XElement element = new XElement(nameof(Cust_Type),
                    new XElement(nameof(Cust_Type.CUSTTYPE_ID), item.CUSTTYPE_ID),
                    new XElement(nameof(Cust_Type.CUSTTYPE_NO), item.CUSTTYPE_NO),
                    new XElement(nameof(Cust_Type.CUSTTYPE_NAME), item.CUSTTYPE_NAME),
                    new XElement(nameof(Cust_Type.REM), item.REM));
                if (xdoc.Root == null)
                {
                    xdoc.Add(new XElement("Cust_TypeS"));
                }
                xdoc.Root.Add(element);
            }
            xdoc.Save(path);
            System.Windows.MessageBox.Show("保存成功!", "提示");
        }

/// <summary>
        /// 删
        /// </summary>
        public void Delete(XDocument xdoc, List<Cust_Type> custTypeList, string path = savePath)
        {
            if (xdoc == null || xdoc.Root == null || custTypeList == null || custTypeList.Count <= 0)
                return;

var element = xdoc.Root.Descendants(nameof(Cust_Type));
            if (element == null)
            {
                return;
            }
            foreach (var item in custTypeList)
            {
                var delElement = element.FirstOrDefault(o => o.Element(nameof(Cust_Type.CUSTTYPE_ID)).Value.Equals(item.CUSTTYPE_ID.ToString()));
                if (delElement != null)
                {
                    delElement.Remove();
                }
            }
            xdoc.Save(path);
            System.Windows.MessageBox.Show("删除成功!", "提示");
        }

/// <summary>
        /// 改
        /// </summary>
        public void Update(XDocument xdoc, List<Cust_Type> custTypeList, string path = savePath)
        {
            if (xdoc == null || xdoc.Root == null || custTypeList == null || custTypeList.Count <= 0)
                return;
            var element = xdoc.Root.Descendants(nameof(Cust_Type));
            if (element == null)
            {
                return;
            }
            foreach (var item in custTypeList)
            {
                var delElement = element.FirstOrDefault(o => o.Element(nameof(Cust_Type.CUSTTYPE_ID)).Value.Equals(item.CUSTTYPE_ID.ToString()));
                if (delElement != null)
                {
                    //delElement.SetElementValue(nameof(Cust_Type.CUSTTYPE_ID), item.CUSTTYPE_ID);
                    delElement.SetElementValue(nameof(Cust_Type.CUSTTYPE_NO), item.CUSTTYPE_NO);
                    delElement.SetElementValue(nameof(Cust_Type.CUSTTYPE_NAME), item.CUSTTYPE_NAME);
                    delElement.SetElementValue(nameof(Cust_Type.REM), item.REM);
                }
            }
            xdoc.Save(path);
            System.Windows.MessageBox.Show("修改成功!", "提示");
        }

/// <summary>
        /// 查
        /// </summary>
        public void Retrieve(XDocument xdoc, List<Cust_Type> custTypeList)
        {
            if (xdoc == null || custTypeList == null || custTypeList.Count <= 0)
                return;
            var element = xdoc.Root.Descendants(nameof(Cust_Type));
            if (element == null)
            {
                return;
            }
        }

/// <summary>
        /// 查
        /// </summary>
        public bool IsExistElement(XDocument xdoc, Cust_Type custType)
        {
            if (xdoc == null || custType == null)
                return false;
            var element = xdoc.Root.Descendants(nameof(Cust_Type));
            if (element == null)
            {
                return false;
            }
            var delElement = element.FirstOrDefault(o => o.Element(nameof(Cust_Type.CUSTTYPE_ID)).Value.Equals(custType.CUSTTYPE_ID));
            if (delElement == null)
            {
                return false;
            }
            return true;
        }

}
}

7、在ViewModels添加相应的ViewModel,内容如下:

using Microsoft.Practices.Prism.Commands;
using Microsoft.Practices.Prism.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WPFDemo.Client.CustType.Models;
using WPFDemo.Client.CustType.Services;
using WPFDemo.Client.Services;
using System.Collections.ObjectModel;
using System.Windows;
using WPFDemo.Client.CustType.Others;

namespace WPFDemo.Client.CustType.ViewModels
{
    /// <summary>
    /// 主界面视图交互的ViewModel
    /// </summary>
    public class MainWindowViewModel : NotificationObject
    {
        #region 变量

/// <summary>
        /// 增
        /// </summary>
        public DelegateCommand CreateCommand { get; set; }

/// <summary>
        /// 删
        /// </summary>
        public DelegateCommand DeleteCommand { get; set; }

/// <summary>
        /// 改
        /// </summary>
        public DelegateCommand UpdateCommand { get; set; }

/// <summary>
        /// 查
        /// </summary>
        public DelegateCommand RetrieveCommand { get; set; }

private List<CustTypeOperatorViewModel> _CustTypeViewModel;

public List<CustTypeOperatorViewModel> CustTypeViewModel
        {
            get { return _CustTypeViewModel; }
            set
            {
                _CustTypeViewModel = value;
                this.RaisePropertyChanged("CustTypeViewModel");
            }
        }

private CustTypeOperatorViewModel custTypeOperatorViewModel;

public CustTypeOperatorViewModel CustTypeOperatorViewModel
        {
            get { return custTypeOperatorViewModel; }
            set
            {
                custTypeOperatorViewModel = value;
                this.RaisePropertyChanged("CustTypeOperatorViewModel");
            }
        }

private ObservableCollection<CustTypeOperatorViewModel> _ObsCCustTypeViewModel;
        public ObservableCollection<CustTypeOperatorViewModel> ObsCCustTypeViewModel
        {
            get { return _ObsCCustTypeViewModel; }
            set
            {
                _ObsCCustTypeViewModel = value;
                this.RaisePropertyChanged("ObsCCustTypeViewModel");
            }
        }

#endregion

public MainWindowViewModel()
        {
            this.LoadCustTypeViewModelData();
            LoadObsCCustTypeViewModelData();
            this.CreateCommand = new DelegateCommand(new Action(this.Create));
            this.DeleteCommand = new DelegateCommand(new Action(this.Delete));
            this.UpdateCommand = new DelegateCommand(new Action(this.Update));
            this.RetrieveCommand = new DelegateCommand(new Action(this.Retrieve));
        }

#region 方法

public void LoadCustTypeViewModelData()
        {
            Services.IDataService ds = new XmlDataService();
            var data = ds.GetCustTypeList();
            this.CustTypeViewModel = new List<CustTypeOperatorViewModel>();
            foreach (var item in data)
            {
                CustTypeOperatorViewModel custTypeViewModel = new CustTypeOperatorViewModel();
                custTypeViewModel.CustType = item;
                this.CustTypeViewModel.Add(custTypeViewModel);
            }
            //this.CustTypeOperatorViewModel = this.ObsCCustTypeViewModel.FirstOrDefault();
        }
        public void LoadObsCCustTypeViewModelData()
        {
            Services.IDataService ds = new XmlDataService();
            var data = ds.GetCustTypeList();
            this.ObsCCustTypeViewModel = new ObservableCollection<CustTypeOperatorViewModel>();
            foreach (var item in data)
            {
                CustTypeOperatorViewModel custTypeViewModel = new CustTypeOperatorViewModel();
                custTypeViewModel.CustType = item;
                this.ObsCCustTypeViewModel.Add(custTypeViewModel);
            }
            this.CustTypeOperatorViewModel = this.ObsCCustTypeViewModel.FirstOrDefault();
        }

/// <summary>
        /// 增
        /// </summary>
        public void Create()
        {
            CustTypeOperatorViewModel obj = new CustTypeOperatorViewModel();
            obj.CustType = new Cust_Type();
            Random ran = new Random();
            obj.CustType.CUSTTYPE_ID = ran.Next(10000);
            this.ObsCCustTypeViewModel.Add(obj);
            SubWindow dlg = new SubWindow(obj, OperatorEnum.Create);
            dlg.ShowDialog();
            //List<Cust_Type> list = this.ObsCCustTypeViewModel.Where(o => o.isSelected == true).Select(i => i.CustType).ToList();
        }

/// <summary>
        /// 删
        /// </summary>
        public void Delete()
        {

List<Cust_Type> list = this.ObsCCustTypeViewModel.Where(o => o.isSelected == true).Select(i => i.CustType).ToList();
            if (list != null)
            {
                if (list.Count > 0)
                {
                    if (MessageBox.Show("是否删除?", "提示", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                    {
                        IDataOperatorService idos = new XmlDataOperatorService();
                        idos.SaveCustTypeList(list, Others.OperatorEnum.Delete);
                        List<CustTypeOperatorViewModel> selectList = this.ObsCCustTypeViewModel.Where(o => o.isSelected == true).Select(i => i).ToList();
                        foreach (var item in selectList)
                        {
                            this.ObsCCustTypeViewModel.Remove(item);
                        }
                        return;
                    }
                }
                if (list.Count == 0)
                {
                    CustTypeOperatorViewModel obj = this.CustTypeOperatorViewModel;
                    if (obj == null)
                    {
                        return;
                    }
                    Cust_Type Cust_Type = new Cust_Type();
                    Cust_Type = obj.CustType;
                    list.Add(Cust_Type);
                    if (MessageBox.Show("是否删除?", "提示", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                    {
                        IDataOperatorService idos = new XmlDataOperatorService();
                        idos.SaveCustTypeList(list, Others.OperatorEnum.Delete);
                        this.ObsCCustTypeViewModel.Remove(obj);
                    }
                }
            }
            MessageBox.Show("没有满足可以删除的条件的删除删除项!", "提示");
        }

/// <summary>
        /// 改
        /// </summary>
        public void Update()
        {
            //CustTypeOperatorViewModel obj = this.ObsCCustTypeViewModel.FirstOrDefault();
            CustTypeOperatorViewModel obj = this.CustTypeOperatorViewModel;
            SubWindow dlg = new SubWindow(obj, OperatorEnum.Update);
            dlg.ShowDialog();
            //System.Windows.MessageBox.Show("修改成功!", "提示");
        }

/// <summary>
        /// 查
        /// </summary>
        public void Retrieve()
        {
            System.Windows.MessageBox.Show("查询成功!", "提示");
        }

#endregion
    }
}

using Microsoft.Practices.Prism.Commands;
using Microsoft.Practices.Prism.ViewModel;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WPFDemo.Client.CustType.Others;
using WPFDemo.Client.CustType.Services;

namespace WPFDemo.Client.CustType.ViewModels
{
    public class SubWindowViewModel : NotificationObject
    {

public DelegateCommand SaveCommand { get; set; }

public DelegateCommand CancelCommand { get; set; }

public OperatorEnum enumData { get; set; }

private CustTypeOperatorViewModel _ObsCCustTypeViewModel;
        public CustTypeOperatorViewModel ObsCCustTypeViewModel
        {
            get { return _ObsCCustTypeViewModel; }
            set
            {
                _ObsCCustTypeViewModel = value;
                this.RaisePropertyChanged("ObsCCustTypeViewModel");
            }
        }

public SubWindowViewModel()
        {
            this.SaveCommand = new DelegateCommand(new Action(SaveData));
            this.CancelCommand = new DelegateCommand(new Action(CancelData));

Services.IDataService ds = new XmlDataService();
            var data = ds.GetCustTypeList();
            this.ObsCCustTypeViewModel = new CustTypeOperatorViewModel();
            ObsCCustTypeViewModel.CustType = data.FirstOrDefault();
           
        }
        public SubWindowViewModel(CustTypeOperatorViewModel CustTypeViewModel, OperatorEnum enumData = OperatorEnum.Update)
        {
            this.enumData = enumData;
            this.SaveCommand = new DelegateCommand(new Action(SaveData));
            this.CancelCommand = new DelegateCommand(new Action(CancelData));

this.ObsCCustTypeViewModel = CustTypeViewModel;
        }
        public void SaveData()
        {
            CustTypeOperatorViewModel ss = this.ObsCCustTypeViewModel;
            IDataOperatorService save = new XmlDataOperatorService();
            save.SaveCustTypeList(new List<Models.Cust_Type> { ss.CustType }, this.enumData);
        }
        public void CancelData()
        {
            System.Windows.MessageBox.Show("取消!", "提示");
        }
    }
}

using Microsoft.Practices.Prism.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WPFDemo.Client.CustType.ViewModels
{
    public class CustTypeOperatorViewModel : NotificationObject
    {
        public Models.Cust_Type CustType { get; set; }

//private Models.Cust_Type custType;

//public Models.Cust_Type CustType
        //{
        //    get { return custType; }
        //    set
        //    {
        //        custType = value;
        //    }
        //}

private bool isselected;

public bool isSelected
        {
            get { return isselected; }
            set
            {
                isselected = value;
                this.RaisePropertyChanged("isSelected");
            }
        }

}
}

8、最后设计MainWindow.xaml主界面的内容,如下:

<Window x:Class="WPFDemo.Client.CustType.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:WPFDemo.Client.CustType"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525" WindowStartupLocation="CenterScreen">
    <Border BorderBrush="Orange" CornerRadius="6" Padding="4">
        <Grid x:Name="root" Margin="4">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"></RowDefinition>
                <RowDefinition Height="*"></RowDefinition>
                <RowDefinition Height="Auto"></RowDefinition>
            </Grid.RowDefinitions>
            <Border BorderThickness="1" Padding="4" CornerRadius="6">
                <StackPanel Orientation="Horizontal" HorizontalAlignment="Left">
                    <ToolBar>
                        <Button Content="查询" Command="{Binding RetrieveCommand}"></Button>
                        <Button Content="新增" Command="{Binding CreateCommand}"></Button>
                        <Button Content="编辑" Command="{Binding UpdateCommand}"></Button>
                        <Button Content="删除" Command="{Binding DeleteCommand}"></Button>
                    </ToolBar>
                </StackPanel>
            </Border>
            <DataGrid x:Name="DataGrid" AutoGenerateColumns="False" Grid.Row="1" CanUserAddRows="False" FontSize="16"
                      CanUserDeleteRows="False" GridLinesVisibility="All" ItemsSource="{Binding ObsCCustTypeViewModel,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" SelectedItem="{Binding CustTypeOperatorViewModel,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}">
                <DataGrid.Columns>
                    <DataGridTextColumn Header="ID" Width="120" Binding="{Binding CustType.CUSTTYPE_ID,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
                    <DataGridTextColumn Header="分类编码" Width="120" Binding="{Binding CustType.CUSTTYPE_NO,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
                    <DataGridTextColumn Header="名称" Width="120" Binding="{Binding CustType.CUSTTYPE_NAME,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
                    <DataGridTextColumn Header="备注" Width="120" Binding="{Binding CustType.REM,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
                    <DataGridTemplateColumn Header="选中" SortMemberPath="isSelected" Width="120">
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <CheckBox IsChecked="{Binding Path=isSelected,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}"
                                          VerticalAlignment="Center" HorizontalAlignment="Center" Command="{Binding see,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type DataGrid}}}"/>
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>
                </DataGrid.Columns>
            </DataGrid>
            <StackPanel Orientation="Horizontal" HorizontalAlignment="Left" Grid.Row="2">
                <StatusBar>
                    <StatusBarItem Content="状态"></StatusBarItem>
                </StatusBar>
            </StackPanel>
        </Grid>
    </Border>

</Window>

相应后台添加

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;
using WPFDemo.Client.CustType.ViewModels;

namespace WPFDemo.Client.CustType
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new MainWindowViewModel();
        }
    }
}
9、另一个弹窗界面,界面设计,内容如下:

<Window x:Class="WPFDemo.Client.CustType.SubWindow"
        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:WPFDemo.Client.CustType"
        mc:Ignorable="d"
        Title="SubWindow" Height="320.858" Width="417.811" WindowStartupLocation="CenterScreen">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Border BorderThickness="1" Padding="4" CornerRadius="6" Grid.Row="0">
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="详情" FontSize="12" FontFamily="Lishu"/>
            </StackPanel>
        </Border>
        <Border BorderThickness="1" Padding="4" CornerRadius="6" Grid.Row="1">
            <StackPanel>
                <Border BorderThickness="1" Padding="4" CornerRadius="6">
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="ID:" FontSize="16" FontFamily="Lishu"/>
                        <TextBox Width="265" Height="Auto" AcceptsReturn="True" VerticalScrollBarVisibility="Auto"
                         TextWrapping="WrapWithOverflow" FontSize="16" FontFamily="Lishu"
                         Text="{Binding ObsCCustTypeViewModel.CustType.CUSTTYPE_ID,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
                    </StackPanel>
                </Border>
                <Border BorderThickness="1" Padding="4" CornerRadius="6">
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="分类编码:" FontSize="16" FontFamily="Lishu"/>
                        <TextBox Width="217" Height="Auto" FontSize="16" FontFamily="Lishu"
                         Text="{Binding ObsCCustTypeViewModel.CustType.CUSTTYPE_NO,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
                    </StackPanel>
                </Border>
                <Border BorderThickness="1" Padding="4" CornerRadius="6">
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="名称:" FontSize="16" FontFamily="Lishu"/>
                        <TextBox Width="250" Height="Auto" FontSize="16" FontFamily="Lishu"
                         Text="{Binding ObsCCustTypeViewModel.CustType.CUSTTYPE_NAME,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
                    </StackPanel>
                </Border>
                <Border BorderThickness="1" Padding="4" CornerRadius="6">
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="说明:" FontSize="16" FontFamily="Lishu"/>
                        <TextBox Width="249" Height="Auto" AcceptsReturn="True" VerticalScrollBarVisibility="Auto"
                         TextWrapping="WrapWithOverflow" FontSize="16" FontFamily="Lishu"
                         Text="{Binding ObsCCustTypeViewModel.CustType.REM,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
                    </StackPanel>
                </Border>
            </StackPanel>
        </Border>
        <Border Padding="4" CornerRadius="6" Grid.Row="2">
            <StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
                <Border Padding="4">
                    <Button Content="保存" Height="30" Width="60" Command="{Binding SaveCommand}"/>
                </Border>
                <Border Padding="4">
                    <Button Content="取消" Height="30" Width="60" Command="{Binding CancelCommand}"/>
                </Border>
            </StackPanel>
        </Border>
    </Grid>
</Window>

后台相应代码内容,如下:

using Microsoft.Practices.Prism.Commands;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
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.Shapes;
using WPFDemo.Client.CustType.Others;
using WPFDemo.Client.CustType.ViewModels;

namespace WPFDemo.Client.CustType
{
    /// <summary>
    /// SubWindow.xaml 的交互逻辑
    /// </summary>
    public partial class SubWindow : Window
    {
        public SubWindow(CustTypeOperatorViewModel CustTypeViewModel, OperatorEnum enumData= OperatorEnum.Update)
        {
            InitializeComponent();
            this.DataContext = new SubWindowViewModel(CustTypeViewModel, enumData);
        }
    }
}

到此为止,以上所有内容基本写完,可以运行啦,界面如下:



使用WPF+MVVM模式的小案例相关推荐

  1. C# WPF MVVM模式Prism框架下事件发布与订阅

    01 - 前言 处理同模块不同窗体之间的通信和不同模块之间不同窗体的通信,Prism提供了一种事件机制,可以在应用程序中低耦合的模块之间进行通信,该机制基于事件聚合器服务,允许发布者和订阅者之间通过事 ...

  2. C# WPF MVVM模式Prism框架从零搭建(经典)

    01 - 前言 目前最新的PRISM的版本是8.1.97,本节以6.3.0.0 讲解,可以在Github上获取PRISM的源码. Prism Github地址:https://github.com/P ...

  3. C# WPF MVVM模式Caliburn.Micro框架下事件发布与订阅

    01 - 前言 处理同模块不同窗体之间的通信和不同模块之间不同窗体的通信,Caliburn提供了一种事件机制,可以在应用程序中低耦合的模块之间进行通信,该机制基于事件聚合器服务,允许发布者和订阅者之间 ...

  4. WPF自学入门(十一)WPF MVVM模式Command命令 WPF自学入门(十)WPF MVVM简单介绍...

    WPF自学入门(十一)WPF MVVM模式Command命令 在WPF自学入门(十)WPF MVVM简单介绍中的示例似乎运行起来没有什么问题,也可以进行更新.但是这并不是我们使用MVVM的正确方式.正 ...

  5. wpf mvvm模式下CommandParameter传递多参

    wpf mvvm模式下CommandParameter传递多参 原文:wpf mvvm模式下CommandParameter传递多参 CommandParameter一般只允许设置一次,所以如果要传递 ...

  6. WPF MVVM模式 发送DataGird表格的数据到另一个页面显示

    WPF MVVM模式 发送DataGird表格的数据到另一个页面显示 这里我们是使用Messenger消息机制把这个页面的表格行数据发送到另一个页面显示,效果如下图: 首先在这个表格页面的ViewMo ...

  7. C# WPF MVVM模式下在主窗体显示子窗体并获取结果

    01 - 前言 在winform中打开一个新的子窗体很简单,直接实例化窗体并show一下就可以: Form2 f2 = new Form2();f2.Show(); 或者 Form2 f2 = new ...

  8. WPF MVVM模式下的无阻塞刷新

    MVVM模式下的无阻塞刷新的两种方法: //传统模式下的无刷新调用(主线程开新线程,新线程又调用主线程来更新UI) //第1步先在线程内部计算出需要绑定的数据 //第2步然后再使用Invoke/Beg ...

  9. WPF MVVM模式的应用——室内监控可视化

    需求 在物联网应用中,可视化端经常需要将实物信息详细的呈现到用户视野之中.在室内环境中,经常可见的设备空调和灯.本次课题主要以室内环境的温湿度和房间用能情况出发,实现室内温湿度和能耗信息的可视化.为了 ...

最新文章

  1. 数据库导出All about Oracle IMP/EXP
  2. 在所有浏览器下一次性测试您的网站
  3. css中的媒体查询_CSS中的媒体查询
  4. MobX基础 ----- 类的静态属性和装饰器
  5. 单选框加了css后显示不出来,layui radio 单选框 效果 显示不来 解决方法
  6. 学linux做笔记本,linux学习之笔记本安装CentOS7
  7. 控制台应用程序中Main函数的args参数
  8. wenz ces123
  9. EZStation如何登陆云端账号、密码?
  10. Tensorflow入门(一)----”搭建图像识别系统“教程整理
  11. Python中单引号,双引号,3个单引号及3个双引号的区别
  12. 转换、刻录DVD影碟光盘教程
  13. ipv4和ipv6地址长度
  14. 下厨房某词条下的所有图片爬取
  15. 固态硬盘是什么接口_5分钟教会你怎么区分M.2固态硬盘接口和协议
  16. 软件测试学习之路-----文本编辑器和计算机基本命令笔记
  17. ERROR 1044 (42000)Access denied for user @localhost to database
  18. 多层神经网络 ——小批量梯度下降法
  19. 自己动手做一个绿色便携版的谷歌浏览器Chrome,可以放入U盘随意带走的
  20. java 集成 atlas

热门文章

  1. 五、Git 与 SVN 区别
  2. 中国E动网陈明华:云计算不拼人 拼“运维能力”
  3. 桌面图标计算机文字,Win7系统桌面图标只有文字没图案怎么办?
  4. 在线问题反馈模块实战(十四):实现在线答疑功能
  5. PageAdmin CMS 环境配置要求
  6. EBS开发_费用类采购订单创建
  7. 计算机应用基础的试卷分析,37班计算机应用基础试卷分析
  8. 地图可视化 | 8月22日重庆山火分布地图及制作方法
  9. Generating fantasy maps——来生成虚拟地图吧!【未完】
  10. html页面点击按钮播放语音,javascript – 当点击按钮时使用jQuery播放音频文件