首页 > 其他分享 > WPF入门教程系列二十九 ——DataGrid使用示例MVVM模式(7)

WPF入门教程系列二十九 ——DataGrid使用示例MVVM模式(7)

时间:2023-06-25 14:12:00浏览次数:47  
标签:ObservableCollection return MVVM 示例 入门教程 Binding using WPF public

WPF入门教程系列目录 WPF入门教程系列二——Application介绍 WPF入门教程系列三——Application介绍(续) WPF入门教程系列四——Dispatcher介绍

WPF入门教程系列五——Window 介绍

WPF入门教程系列十一——依赖属性(一) WPF入门教程系列十五——WPF中的数据绑定(一)   接上文WPF入门教程系列二十八 ——DataGrid使用示例MVVM模式(6)

    13.通过Command指令,传递了下拉框所选择的省份,datagrid自动显示相应省份的城市信息,但是以上示例中有一个Bug,就是下拉框中绑定的数据无法显示。

这是由于DataGridComboBoxColumn若要填充下拉列表,请先使用以下选项之一设置 ItemsSource 属性 ComboBox :

    1)静态资源。 使用StaticResource 标记扩展。

    2)x:Static 代码实体。 使用x:Static 标记扩展。

    3)类型的内联集合 ComboBoxItem 。

14.比较适合的绑定方式是  2)x:Static 代码实体。 使用x:Static 标记扩展需要添加相应的命名空间。在Visual Studio 2022中打开MainWindows.xmal文件,并在文件的开头添加如下命名空间。           

  xmlns:v="clr-namespace:WpfGridDemo.NET7.ViewModel"

15. 在Visual Studio 2022中打开MainWindows.xmal文件。对DataGridComboBoxColumn的ItemsSource进行了数据绑定。具体代码如下:

<DataGridComboBoxColumn Header="城市" Width="120"  x:Name="cboCity" 
ItemsSource="{x:Static v:MainWindowVM.GridCityList}" ClipboardContentBinding="{x:Null}" SelectedValuePath="Code"
SelectedValueBinding="{Binding Path=CityCode,UpdateSourceTrigger=PropertyChanged}"
DisplayMemberPath="Name" SelectedItemBinding="{x:Null}" />
16.在Visual Studio 2022的解决方案资源管理器中,找到MainWindowVM.cs文件,将GridCityList属性改为静态属性,用于绑定DataGridComboBoxColumn的ItemsSource。具体如下代码:
        private static ObservableCollection<City> cityList;
        public static ObservableCollection<City> GridCityList
        {

            get { return cityList; }
            set
            {

                cityList = value;
                new ViewModelBase().RaisePropertyChanged("GridCityList");
            }

        }
17.在Visual Studio 2022中按F5键,启动WPF应用程序。然后使用鼠标点击省份下拉框,能够看到,界面中DataGrid中的数据,随着下拉框的变化而随之变化,但是城市下拉框中却没有任何数据。看来绑定失效了。如下图。

 

 

 

 

 

18. 使用静态代码实体的方式,实现省市县联动失败了。又不想使用其他两种方式。在一阵猛于虎的搜索之后,发现一种实现方式。在Visual Studio 2022中打开MainWindows.xmal文件。对DataGridComboBoxColumn进行了数据绑定。具体代码如下:

<DataGridComboBoxColumn Header="城市(Style)" SelectedValuePath="Code"
SelectedValueBinding="{Binding Path=CityCode,UpdateSourceTrigger=PropertyChanged}"
DisplayMemberPath="Name" SelectedItemBinding="{x:Null}" Width="1*"> <DataGridComboBoxColumn.EditingElementStyle> <Style TargetType="ComboBox"> <Setter Property="ItemsSource"
Value="{Binding Path=DataContext.GridCity,ElementName=gridArea}" /> </Style> </DataGridComboBoxColumn.EditingElementStyle> <DataGridComboBoxColumn.ElementStyle> <Style TargetType="ComboBox"> <Setter Property="ItemsSource"
Value="{Binding Path=DataContext.GridCity,ElementName=gridArea}" /> </Style> </DataGridComboBoxColumn.ElementStyle> </DataGridComboBoxColumn>
              

19.在Visual Studio 2022的解决方案资源管理器中,找到MainWindowVM.cs文件,添加一个GridCity属性,用于绑定DataGridComboBoxColumn的ItemsSource。以下是属性代码,更完整的代码,请参见下面类的完整代码。

private ObservableCollection<City> listCity;

        public ObservableCollection<City> GridCity
        {

            get { return listCity; }
            set
            {
                listCity = value;
                RaisePropertyChanged("GridCity");
            }
        }
20.MainWindow.xmal的全部代码如下:
<Window x:Class="WpfGridDemo.NET7.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:be="http://schemas.microsoft.com/xaml/behaviors"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfGridDemo.NET7"
          xmlns:v="clr-namespace:WpfGridDemo.NET7.ViewModel"
        mc:Ignorable="d"
        Title="MainWindow" Height="600" Width="960" Loaded="Window_Loaded" >

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="100"></RowDefinition>
            <RowDefinition Height="*"></RowDefinition>
            <RowDefinition Height="25"></RowDefinition>
        </Grid.RowDefinitions>
        <WrapPanel Grid.Row="0" HorizontalAlignment="Left">
            <ComboBox x:Name="cboProvince" DisplayMemberPath="Name" SelectedValuePath="Code" >
                <be:Interaction.Triggers>
                    <be:EventTrigger EventName="SelectionChanged">
                        <be:InvokeCommandAction Command="{Binding ProviceChangedAction}"
CommandParameter="{Binding ElementName=cboProvince}"/> </be:EventTrigger> </be:Interaction.Triggers> </ComboBox> </WrapPanel> <DataGrid x:Name="gridArea" Grid.Row="1" ItemsSource="{Binding GridAreaList}"
AutoGenerateColumns="False" HorizontalAlignment="Left" VerticalAlignment="Top"
SelectedItem="{Binding Path=AreaVM,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"> <DataGrid.Columns> <DataGridComboBoxColumn Header="城市" Width="120" x:Name="cboCity"
ItemsSource="{x:Static v:MainWindowVM.GridCityList}" ClipboardContentBinding="{x:Null}" SelectedValuePath="Code"
SelectedValueBinding="{Binding Path=CityCode,UpdateSourceTrigger=PropertyChanged}"
DisplayMemberPath="Name" SelectedItemBinding="{x:Null}" /> <DataGridComboBoxColumn Header="城市(Style)" SelectedValuePath="Code"
SelectedValueBinding="{Binding Path=CityCode,UpdateSourceTrigger=PropertyChanged}"
DisplayMemberPath="Name" SelectedItemBinding="{x:Null}" Width="1*"> <DataGridComboBoxColumn.EditingElementStyle> <Style TargetType="ComboBox"> <Setter Property="ItemsSource"
Value="{Binding Path=DataContext.GridCity,ElementName=gridArea}" /> </Style> </DataGridComboBoxColumn.EditingElementStyle> <DataGridComboBoxColumn.ElementStyle> <Style TargetType="ComboBox"> <Setter Property="ItemsSource"
Value="{Binding Path=DataContext.GridCity,ElementName=gridArea}" /> </Style> </DataGridComboBoxColumn.ElementStyle> </DataGridComboBoxColumn> <DataGridTextColumn Header="县区镇" Width="*"
Binding="{Binding Name}" ClipboardContentBinding="{x:Null}"/> <DataGridTextColumn Header="邮编" Width="100"
Binding="{Binding Code}" ClipboardContentBinding="{x:Null}"/> <DataGridTextColumn Header="创建时间" Width="160"
Binding="{Binding Created}" ClipboardContentBinding="{x:Null}"/> <DataGridTextColumn Header="更新时间" Width="160"
Binding="{Binding Updated}" ClipboardContentBinding="{x:Null}"/> </DataGrid.Columns> </DataGrid> <WrapPanel Grid.Row="2"> <Button x:Name="btnRefresh" Height="22" Width="120" Click="btnRefresh_Click">刷新</Button>
<Button x:Name="btnSave" Height="22" Width="120" Command="{Binding ClickSaveAction}" >保存</Button> </WrapPanel> </Grid> </Window>

 

21. MainWindowsVM类的完整代码,如下:
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.DirectoryServices.ActiveDirectory;

using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;

using System.Windows.Input;
using WpfGridDemo.NET7.Entitys;
 

namespace WpfGridDemo.NET7.ViewModel
{

    public class MainWindowVM: ViewModelBase
    {

        public MainWindowVM() {
            cityList = new ObservableCollection<City>();

            areaList = new ObservableCollection<Area>();

            listCity = new ObservableCollection<City>();   

        }

        private Area m_Area;

        /// <summary>
        /// 县镇区数据
        /// </summary>
        public Area AreaVM

        {

            get { return m_Area; }

            set { m_Area = value; }

        }

        private string m_Province_Code;

        /// <summary>
        /// 省--代码
        /// </summary>

        public string ProvinceCode { get => m_Province_Code; set => m_Province_Code = value; }

        private ObservableCollection<Area> areaList;

         public ObservableCollection<Area> GridAreaList
         {
             get { return areaList; }

             set
             {

                areaList = value;
                 RaisePropertyChanged("GridAreaList");

             }

        }

        private static ObservableCollection<City> cityList;

        public static ObservableCollection<City> GridCityList
        {

            get { return cityList; }

            set
            {
                cityList = value;
                new ViewModelBase().RaisePropertyChanged("GridCityList");
            }
        } 

        private ObservableCollection<City> listCity;

        public ObservableCollection<City> GridCity

        {
            get { return listCity; }
            set

            {
                listCity = value;
                RaisePropertyChanged("GridCity");
            }

        }

        /// <summary>
        /// 命令要执行的方法
        /// </summary>
        void SaveExecute()
        {

            try
            {

                GridDbContext db = new GridDbContext();
                var list=db.Area.AsTracking().ToList();
                Area modifyArea = list.Where(x=>x.Id==AreaVM.Id).FirstOrDefault();

                if (modifyArea != null)

                {

                    modifyArea.Name = AreaVM.Name;

                    modifyArea.Updated = DateTime.Now;

                    db.SaveChanges();

                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

 

        /// <summary>
        /// 命令是否可以执行
        /// </summary>
        /// <returns></returns>
        bool CanSaveExecute()
        {
            return false;
        }

 

        /// <summary>
        /// 创建新命令
        /// </summary>
        public ICommand ClickSaveAction
        {
            get
            {
                return new Command.SaveCommand(SaveExecute, CanSaveExecute);
            }

        }

        //combobox
        /// <summary>
        /// 命令要执行的方法
        /// </summary>
        void ProviceSelectionChangedExecute(object sender)
        {
            try
            {

                if (sender is ComboBox)

                {

                    ComboBox drp=sender as ComboBox;

                    ProvinceCode=drp.SelectedValue.ToString();

                    GridDbContext db = new GridDbContext();

                    var list = db.City.AsTracking().ToList();

                    List<City> citys = list.Where(x => x.ProvinceCode == ProvinceCode).ToList();

                    var cityCodes = from city in citys

                                    select city.Code;

                    List<Area> areas = db.Area.AsTracking().ToList()
.Where(x => cityCodes.Contains(x.CityCode)).ToList(); areaList.Clear(); if (areas!=null) { areas.ForEach((t) => { areaList.Add(t); } ); } cityList.Clear(); if (citys != null) { citys.ForEach((t) => { cityList.Add(t); } ); } listCity.Clear(); if (citys != null) { citys.ForEach((t) => { listCity.Add(t); } ); } } } catch (Exception ex) { throw ex; } } /// <summary> /// 命令是否可以执行 /// </summary> /// <returns></returns> bool CanSelectionChangedExecute() { return true; } /// <summary> /// 创建新命令 /// </summary> public ICommand ProviceChangedAction { get { return new Command.ProvinceChangedCommand<object>(ProviceSelectionChangedExecute
, CanSelectionChangedExecute); } } } }

22.在Visual Studio 2022中按F5键,启动WPF应用程序。然后使用鼠标点击省份下拉框,能够看到,界面中DataGrid中的数据,随着下拉框的变化而随之变化,其中使用静态实体代码绑定的城市下拉框中却没有任何数据。使用使用非静态资源,在<DataGridComboBoxColumn.EditingElementStyle>与 <DataGridComboBoxColumn.ElementStyle>两个样式中绑定combobox的itemSource属性方式,效果有效。如下图。

 

标签:ObservableCollection,return,MVVM,示例,入门教程,Binding,using,WPF,public
From: https://www.cnblogs.com/chillsrc/p/17502789.html

相关文章

  • Linux使用HTTP代码示例
    以下是使用Linux命令行发送HTTP请求的示例:1.使用curl命令发送GET请求:```curl ExampleDomain```2.使用curl命令发送POST请求:```curl-XPOST-d"param1=value1&param2=value2" ExampleDomain```3.使用wget命令发送GET请求:```wget ExampleDomain```4.使用wget命令发送POST......
  • esq32蓝牙组网节点示例学习
    如何确定一个mesh网络设置好共同的matchid,这样配网的时候就可以将id相同的板子配置到一个mesh即可将需要配网的设备的UID设置成和matchID一样即可完成一个mesh网络的构建蓝牙开关的配网实验本文利用两个esp32开发板。一块用作prov并且注册client模型,第二块板子注册server......
  • Vue(五):Vue中的MVVM
    <!DOCTYPEhtml><html><head><metacharset="utf-8"><title>Vue中的MVVM</title><scripttype="text/javascript"src="../js/vue.js"></script></head><body>......
  • 密码学:凯撒密码(移位密码)原理、加密与解密(Python代码示例)
    原理凯撒密码(移位密码):是一种替换加密,明文中的所有字母都在字母表上向后或向前按照一个固定数目进行偏移后被替换成密文。例如,偏移量为3位的时候:A对应D,B对应E,C对应F等当偏移量为13位的时候,凯撒密码又叫回转密码(ROT13):明文加密得到密文,密文再加密就会得到明文(因为偏移量为13位,一共......
  • C++入门教程
    C++入门教程----------------------------------------------------------一.初识C++---------------------------------------------------------1.什么是C++.c++是一种较为基础的编程语言,虽然没有Python,Scratch那么高级,但是它应用范围很广.不论是信息奥赛还是国......
  • 人工智能在智能家居控制器中的应用,打造智慧家居控制器的100篇热门博客文章标题示例
    目录引言随着人工智能技术的不断发展,智能家居控制器作为人工智能在家居领域的一个重要应用,其重要性日益凸显。智能家居控制器不仅可以实现智能化的家居控制,还可以提高家居安全性、便利性和舒适性。本文将介绍人工智能在智能家居控制器中的应用,以及打造智慧家居控制器的100篇热......
  • Android车载应用系统开发入门教程(非常详细)从零基础入门到精通,看完这一篇就够了
    前言众所周知,国内的安卓市场内卷极其严重,原生应用开发可谓是寸步难行,但整个Android生态却无比繁荣,手机、平板、电视、音视频等等,特别是在智能汽车+电动汽车的浪潮下,车载行业成为许多Android人竞相奔走的行业,薪资待遇以及岗位招聘呈上涨趋势。对于涉事多年的「老Android人」来说,转行......
  • 最佳SQL Server 2008入门教程
    媒体评论“本书是SQLServer数据库初学者的明智选择。它不仅很好地介绍了SQLServer的主要特性,还深入浅出地阐述了数据库开发和设计的一般性概念。”——Amazon读者评论“即使是我这种原本对SQLServer一无所知的人,在开始读这本书后,也会兴趣陡增,热情高涨,满怀信心地靠它从新手变为专......
  • 三菱通过485bd板 CRC指令通讯示例 不含详细校验程序。
    三菱通过485bd板CRC指令通讯示例不含详细校验程序。所需硬件:三菱FX3Uplc,FX3U485BD通讯板,台达VFD-M变頻器。可以实现的功能:控制方面,正反转停止,頻率设定;读取运行状态、运行頻率、頻率指令、运行电流。内容包括plc程序,触摸屏程序,变頻器参数设置,通讯接线,视频教程。另外说明,别......
  • FX3U使用FB方式,三菱专用指令通讯四台三菱E700变頻器示例程序
    FX3U使用FB方式,三菱专用指令通讯四台三菱E700变頻器示例程序需要硬件:fx3u/fx3s/fx3g(ver1.1以上),配套485bd通讯扩展板,三菱E500,E700,D700,S500等支持三菱专用协议变频器。采用FB方式编写,功能块调用,程序易懂明了,想增加更多台很方便。可实现功能1,控制正反转停止,频率设定,实时频率电流......