首页 > 其他分享 >WPF中实现MVVM

WPF中实现MVVM

时间:2022-11-28 10:12:18浏览次数:39  
标签:set string MVVM get 实现 sql new WPF public

MVVM(Model-View-ViewModel):Model指的是后台传递的数据,View指的是所看到的页面。ViewModel是mvvm模式的核心,它是连接view和model的桥梁。它有两个方向:一是将模型转化成视图,即将后端传递的数据转化成所看到的页面。实现的方式是: 数据绑定。二是将视图转化成模型,即将所看到的页面转化成后端的数据   Wpf 使用MVVM模式的优点:   1.结构清晰明朗,上手成本低,一个新人也能快速的定位自己需要改动代码的位置。 2.耦合度低,更改WPF控件不影响数据结构,更改代码成本低。 3.可重用性高,比如一个处理逻辑放到ViewModel模块中,其他界面如果要用掉直接调用即可。 当然并不是所有的项目都去使用MVVM开发,一些简单的我们也可以按照正常的开发。   使用WPF MvvM模式 在先创建的项目中新建三个文件夹: Views,Models,ViewModels文件夹: Views文件夹中存放视图; Models:文件夹中存放模式; ViewModels文件夹中存放业务逻辑; 当做完这些操作时项目的文件目录是这样的:  

 

 

下面这个示例是我的实现: 视图:(MainWindow.xaml)  

 

 

视图代码:
<Window.Resources>
        <Style TargetType="TextBlock">
            <Setter Property="FontSize" Value="18"></Setter>
            <Setter Property="HorizontalAlignment" Value="Center"></Setter>
            <Setter Property="FontWeight" Value="Black"></Setter>
            <Setter Property="Margin" Value="0 30"></Setter>
            <Setter Property="Width" Value="350"></Setter>
        </Style>
        <Style TargetType="TextBox">
            <Setter Property="Width" Value="150"></Setter>
            <Setter Property="Height" Value="30"></Setter>
            <Setter Property="Margin" Value="10 0 0 0"></Setter>
            <Setter Property="HorizontalAlignment" Value="Center"></Setter>
            <Setter Property="VerticalAlignment" Value="Center"></Setter>
            <Setter Property="FontSize" Value="16"></Setter>
            <Setter Property="Padding" Value="3"></Setter>
        </Style>
        <Style TargetType="Button">
            <Setter Property="BorderThickness" Value="0"></Setter>
            <Setter Property="Background" Value="Blue"></Setter>
            <Setter Property="Width" Value="100"></Setter>
            <Setter Property="HorizontalAlignment" Value="Center"></Setter>
            <Setter Property="Height" Value="40"></Setter>
            <Setter Property="FontSize" Value="16"></Setter>
            <Setter Property="FontWeight" Value="Black"></Setter>
            <Setter Property="Foreground" Value="#FFF"></Setter>
            <Setter Property="Margin" Value="10 0 0 0"></Setter>
        </Style>
    </Window.Resources>
    
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="auto"></RowDefinition>
            <RowDefinition> </RowDefinition>
        </Grid.RowDefinitions>
        <StackPanel Orientation="Horizontal">
     
            <TextBlock  Text="{Binding Title}"></TextBlock>
            <!--<TextBox Text="{Binding Mcontent}"></TextBox>-->
            <!--Command是一个命令类型的属性
            获取或设置按下此按钮时要调用的命令。
            -->
            <Button Content="点击" x:Name="Search" Command="{Binding SearchCommand}"></Button>
        </StackPanel>
        <DataGrid x:Name="Daone" Grid.Row="1"  IsReadOnly="True"  HorizontalAlignment="Stretch" AutoGenerateColumns="False" 
                  CanUserResizeColumns="False" CanUserResizeRows="False"  SelectionMode="Single" 
                 AlternationCount="2" ItemsSource="{Binding StaffS}" RowHeaderWidth="0" CanUserAddRows="False" Background="White"  >
            <!--给整个表头添加颜色开始-->
            <DataGrid.ColumnHeaderStyle>
                <Style TargetType="DataGridColumnHeader">
                    <Setter Property="Background">
                        <Setter.Value>
                            <LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
                                <GradientStop Color="White" Offset="0"/>
                                <GradientStop Color="LightBlue" Offset="0.5"/>
                                <GradientStop Color="White" Offset="1"/>
                            </LinearGradientBrush>
                        </Setter.Value>
                    </Setter>
                    <Setter Property="Foreground" Value="Black"/>
                    <Setter Property="FontSize" Value="13" />
                </Style>
            </DataGrid.ColumnHeaderStyle>
             <!--隔行变色-->
            <DataGrid.RowStyle>
                <Style TargetType="{x:Type DataGridRow}">
                    <Setter Property="FontSize" Value="12"></Setter>
                    <Style.Triggers>
                        <Trigger Property="ItemsControl.AlternationIndex" Value="0">
                            <Setter Property="Background" Value="#cbedfa"></Setter>
                        </Trigger>
                        <Trigger Property="ItemsControl.AlternationIndex" Value="1">
                            <Setter Property="Background" Value="#FFF"></Setter>
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </DataGrid.RowStyle>
            <DataGrid.Columns>
                <DataGridTextColumn Header="Id" Width="*" Binding="{Binding Id}"></DataGridTextColumn>
                <DataGridTextColumn Header="姓名" Width="*"  Binding="{Binding Name}"></DataGridTextColumn>

                <DataGridTextColumn Header="地址" Width="*"  Binding="{Binding address}"></DataGridTextColumn>
                <DataGridTextColumn Header="年龄" Width="*"  Binding="{Binding age}"></DataGridTextColumn>

                <DataGridTextColumn Header="性别" Width="*"  Binding="{Binding gender}"></DataGridTextColumn>

                <DataGridTextColumn Header="联系电话"  Width="*"  Binding="{Binding Contactnumber}"></DataGridTextColumn>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>

  

  MainWindow.xaml.cs ` 
 public MainWindow()
        {
            InitializeComponent();
            //页面的数据绑定
            this.DataContext =new MainViewModel();

            //这里实现的是视图的关闭;
            //WindowManager.Reister<MainWindow>("MainWindow");
            //表格的数据绑定
             //Daone.DataContext = new MainViewModel();
           

        }

 

模型 Staff.cs
namespace WpfApp2.Models
{
    public class Staff
    {
        
        public int Id { get; set; }
        //名字
        public string Name { get; set; }
        //年龄
        public string age { get; set; }
        //性别
        public Gender gender { get; set; }
        //家庭地址
        public string address { get; set; }
        //联系电话
        public string Contactnumber { get; set; }

    }
    public enum Gender
    {
        女 = 0,
        男 = 1,
    }
}

  

视图模型 MainViewModel.cs
public class MainViewModel:ViewModelUtil
    {
        //observableCollection 表示一个动态数据集,该集合在项目获取时提供通知
        //添加、删除或刷新整个列表时。.
        ObservableCollection<Staff> staffs=new ObservableCollection<Staff>();

        public ObservableCollection<Staff> StaffS
        { 
            //get 用于获取属性的值,
            get { return staffs; }
            //Set  用于设置字段的值;
            set { StaffS = value;RaisPropertyChanged("StaffS"); }
        }
    

        public MainViewModel()
        {
            #region 数据源
            Selectstaff();




            #endregion
            //#region Linq语句 的格式
            //var linqList = list.Where(t => t < 10)              //列表中值小于10
            //           .GroupBy(t => t)                     //分组
            //           .Where(t => t.Count() > 1)           //分组后出现次数大于1
            //           .OrderByDescending(t => t.Count())   //按照出现次数倒序
            //           .Select(t => t.Key);                 //选择值
            //#endregion
            SearchCommand = new RelayCommand((arg) =>
            { 
                //将窗口新增值哈希表;
                WindowManager.Reister<AddStaff>("AddStaff");
                //打开窗口
                WindowManager.Show("AddStaff",new AddViewModel());

              
                //MessageBox.Show("你点击了一个按钮");
                //新增
                //staffs.Add(new Staff() { Id = 3, Name = "小黄", address = "China", age = "19", gender = (Gender)0, Contactnumber = "15309878644" });
                //修改
                //staffs[0] = new Staff() { Id = 3, Name = "小黄", address = "China", age = "19", gender = (Gender)0, Contactnumber = "15309878644" };
                //删除
                //staffs.RemoveAt(1);
                //清空全部;
                //  staffs.Clear();

            });
        }
        public void Selectstaff()
        {
            string sql = "Select * from Staff";
            SqlDataReader data = SqlCon.Reader(sql);
            while (data.Read())
            {
                staffs.Add(new Staff() { Id = Convert.ToInt32(data["Id"]), Name = data["Name"].ToString(), age = data["age"].ToString(), gender = (Gender)Convert.ToInt32(data["gender"]), address = data["address"].ToString(), Contactnumber = data["Conrtactnumber"].ToString() });
            }
        }
        private string mcontent ;
        public string Mcontent
        {
            get { return mcontent; }
            set { mcontent = value; }   
        }
        private string title = "标题";
        public string Title 
        {
            get { return title; }
            set { title = value; }
        }
       
        //搜索 SearchCommand
        public ICommand SearchCommand { get; set; }
    }

  

ViewModelUtil.cs
namespace WpfApp2.ViewModels
{ 
    //INotifyPropertyChanged 通知客户端属性值以修改;
     public class ViewModelUtil : INotifyPropertyChanged
    {  
        //在属性值改变时发生;
        public event PropertyChangedEventHandler? PropertyChanged;
        public void RaisPropertyChanged(string propertyName )
        {
            if (propertyName != null)
            {
                //Invoke调用    初始化PropertyChangedEventArgs;  propertyName 以更改属性的名称 
                PropertyChanged?.Invoke( this, new PropertyChangedEventArgs( propertyName ) );
            }   
        }
    }
}

  

RelayCommand.cs
namespace WpfApp2.ViewModels
{
    public class RelayCommand : ICommand
    {
        //EventHandler 表示将处理没有事件数据的事件的方法。
        public event EventHandler? CanExecuteChanged;
        //封装具有单个参数且不返回值的方法;
        private Action<object> _ExecuteAction;
        //构造函数
        public RelayCommand(Action<object> action)
        {
            _ExecuteAction= action;
        }
        public bool CanExecute(object? parameter)
        {
            return true;
        }

        public void Execute(object? parameter)
        {
            //Invoke 调用
          _ExecuteAction?.Invoke(parameter);
        }
    }
}
 访问数据库是通过Ado.Net 写的
  public class SqlCon
    {
        public static readonly string SqlSouer = "Server=DESKTOP-09OGCCU;Initial Catalog=Met;User Id=sa1;Password=sa123";

        ///// <summary>
        ///// 新增
        ///// </summary>
        ///// <param name="sql">用于操作的SQL语句</param>
        //public static string SqlAdd(string sql )
        //{
        //    string msg = "";
        //    using (SqlConnection connection=new SqlConnection(SqlSouer))
        //    { 
        //        //打开数据库
        //        connection.Open();
        //        //创建命令对象,指定要执行SQL语句与连接对象;
        //        SqlCommand sqlCommand = new SqlCommand(sql, connection);
        //        //执行,返回受影响行数;
        //        int rows=sqlCommand.ExecuteNonQuery();
        //        if(rows > 0)
        //        {
        //              msg = "执行成功";
        //        }
                
        //        ////关闭数据库
        //        //connection.Close();
        //    }
        //    return msg;
        //}

        ///// <summary>
        ///// 查询
        ///// </summary>
        ///// <param name="sql"></param>
        ///// <param name="Met"></param>
        ///// <returns></returns>
        //public static SqlDataReader Sqlinq(string sql,object Met)
        //{
        //  Dictionary<string, string> result = new Dictionary<string, string>();
        //    using (SqlConnection connection = new SqlConnection(SqlSouer))
        //    {
        //        connection.Open();
        //        SqlCommand sqlCommand = new SqlCommand(sql, connection);
        //        //执行查询返回结果集;
        //        SqlDataReader reader = sqlCommand.ExecuteReader();
        //        return reader;
        //    }
           
        //}
        /// <summary>
        /// 完成增,删,改
        /// </summary>
        /// <param name="sql">将要执行的sql</param>
        /// <param name="ps">可变参数,指定sql中的参数</param>
        /// <returns></returns>
        /// params 可变参数 这里的可变是个数可变;
        /// params 修饰在参数的前面且参数类型得是一维数组类型;
        /// params 修饰的参数默认是可以不传递的
        /// params 参数不能用ref或out修饰且不能手动给默认值;
        public static int Execute(string sql,params SqlParameter[] ps)
        {
            foreach(SqlParameter p in ps)
            {
                if (p.Value == null)
                {
                    p.Value=DBNull.Value;
                }
            }
            using(SqlConnection conn = new SqlConnection(SqlSouer))
            {   
                //打开连接
                conn.Open();
                //创建命令对象,指定sql与连接对象conn;
                SqlCommand cmd =new SqlCommand(sql,conn);
                //指定参数
                if(ps != null) cmd.Parameters.AddRange(ps);
                //执行sql 命令返回影响行数;
                return cmd.ExecuteNonQuery();

            }
        }
        /// <summary>
        /// 完成查询;
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="ps"></param>
        /// <returns></returns>
        public static SqlDataReader Reader(String sql,params SqlParameter[] ps)
        {
            SqlConnection con = new SqlConnection(SqlSouer);
            
                con.Open();
                SqlCommand cmd=new SqlCommand(sql,con);
                if(ps != null ) cmd.Parameters.AddRange(ps);
                return cmd.ExecuteReader(CommandBehavior.CloseConnection);
            
        }
    }

  

上面的代码有注释,没有什么好说的(我自己也是刚刚学完,上面的代码相当于我的笔记)   

标签:set,string,MVVM,get,实现,sql,new,WPF,public
From: https://www.cnblogs.com/shengkun008/p/16931455.html

相关文章