无法创建ViewModel

时间:2018-12-28 09:30:09

标签: c# wpf

我是MVVM和WPF的新手。

我创建了一个简单的加法应用程序,该应用程序将两个数字作为输入,并将给定的数字添加到数据库中,然后在文本框中提供结果。

该应用程序正常运行。

但是windows.xaml会引发以下错误

无法创建ViewModel类型的实例

Windows.xaml

<Window x:Class="addition.Window1"
         xmlns:vm="clr-namespace:addition.ViewModel" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <Window.DataContext>
        <vm:ViewModel/>
    </Window.DataContext>
    <Grid>

        <Label Height="28" Margin="28,54,0,0" Name="Number1" VerticalAlignment="Top" HorizontalAlignment="Left" Width="48">Number</Label>
        <TextBox Height="28" Margin="112,56,46,0"  Text ="{Binding Path = FirstArgument}"   Name="textBox1" VerticalAlignment="Top" />
        <Label Margin="28,106,0,128" Name="Number2" Width="58" HorizontalAlignment="Left">Number1</Label>
        <TextBox Height="28" Margin="112,120,46,120" Text ="{Binding  Path = secondargument}" Name="textBox2" />
        <Label Height="28" Margin="28,0,0,75" Name="label1" VerticalAlignment="Bottom" HorizontalAlignment="Left" Width="58">Number2</Label>
        <TextBox Height="23" Margin="112,0,46,68" Name="textBox3" Text="{Binding Path = Addedargument}" VerticalAlignment="Bottom" />
        <Button Height="23"  HorizontalAlignment="Left" Margin="39,0,0,16" Name="button1" VerticalAlignment="Bottom" Width="75" Command="{Binding AddNew}">Button</Button>
    </Grid>
</Window>

当我在视图模型中实例化数据库连接类时,发生错误。当我注释掉databaseconnetion类时,该问题得到解决。

ViewModel.cs:

using addition.Model;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.Design;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.ComponentModel;

namespace addition.ViewModel
{
    class ViewModel : INotifyPropertyChanged
    {
        private Number n1 = new Number();
        int num, num1;
//The issue is resolved when i comment the below instantiation

        databaseconnection d1 = new databaseconnection();

        public RelayCommand AddNew { get; set; }

        private string _number1;

        public string FirstArgument
        {

            get { return this._number1; }
            set
            {
                this._number1 = value;
                if (int.TryParse(_number1.ToString(), out num))
                {
                    this.n1.number1 = num;
                    this.OnPropertyChanged("FirstArgument");

                }
                else { MessageBox.Show("The given Value is not a Number "); }

            }
        }
        private string _number2;

        public string secondargument
        {
            get { return this._number2; }

            set
            {
                this._number2 = value;
                if (int.TryParse(_number2.ToString(), out num1))
                {
                    this.n1.number2 = num1;
                    this.OnPropertyChanged("secondargument");
                }
                else { MessageBox.Show("The given Value is not a Number "); }

            }
        }

        private string _number3;

        public string Addedargument
        {
            get { return this._number3; }
            set
            {
                this._number3 = value;
                this.OnPropertyChanged("Addedargument");
            }
        }

        public ViewModel()
        {

                AddNew = new RelayCommand(o => AddNumbers());

        }


        public void AddNumbers()
        {

                d1.data(this);


        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        #endregion

    }


    class databaseconnection
    {
        static string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MYConnectionString"].ConnectionString;
        public void data(ViewModel m1)
        {
            string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MYConnectionString"].ConnectionString;

//The query is prone to sql injection 

        string sql = "SELECT " + "( cast( " + m1.FirstArgument +" as int) + " + "cast( " + m1.secondargument + " as int) )" + " as Addedargument";
            // MessageBox.Show(sql);
            DataSet ds = new DataSet();
            using (var connection = new SqlConnection(connectionString))
            {
                using (var command = new SqlCommand(sql, connection))
                {
                    SqlDataAdapter dataadapter = new SqlDataAdapter(command);
                    connection.Open();
                    using (SqlDataReader reader = command.ExecuteReader())
                    {

                        if (reader.Read())
                        {

                            m1.Addedargument = reader["Addedargument"].ToString();
                        }
                    }
                }
            }
        }
    }
}

问题:

  • 因为我是初次通过mvvm进入wpf,所以我不确定是否数据库 连接应该发生在ViewModel或Model中。请告诉我 我的方法是否正确。
  • 为什么当我出现错误时 实例化该类,即使程序和逻辑在 运行。问题是由于以下原因,我无法设计应用程序 错误。错误发生在

     <Window.DataContext>
           <vm:ViewModel/>
       </Window.DataContext>
    

1 个答案:

答案 0 :(得分:0)

我认为您应该评论静态字段static string connectionString 在类databaseconnection中,或在类构造函数中初始化该字段。