无法创建 ViewModel 类型的实例

拉姆吉

我是 MVVM 和 WPF 的新手。

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

该应用程序运行良好。

但是 windows.xaml 抛出以下错误

无法创建 ViewModel 类型的实例

视窗.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 类时,问题得到解决。

视图模型.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>
    
弗雷迪·阿德里亚诺·希门尼斯·马丁内斯

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

WPF:无法创建类型的实例

来自分类Dev

为新类型创建实例

来自分类Dev

确保每个子UserControl创建自己的ViewModel实例

来自分类Dev

无法实例化类型

来自分类Dev

创建泛型类型的实例

来自分类Dev

使用Autofac立即创建ViewModel实例

来自分类Dev

无法实例化AppiumDriver类型

来自分类Dev

在ViewModel中创建控件实例

来自分类Dev

无法创建类型X的实例。类型是接口或抽象类,无法实例化

来自分类Dev

Minecraft Modding“无法实例化类型”,创建CreativeTab

来自分类Dev

创建未知类型的实例

来自分类Dev

如何创建未知类型的实例?

来自分类Dev

Scala创建别名类型的实例

来自分类Dev

为什么无法创建类型参数的实例?

来自分类Dev

无法创建ViewModel类的实例

来自分类Dev

无法在Android MVVM中创建ViewModel类的实例

来自分类Dev

无法为[type:Factory,primary_type:'yodgorbek.komilov.musobaqayangiliklari.viewmodel.MainViewModel'创建实例吗?

来自分类Dev

在Android中使用Hilt后无法创建ViewModel实例

来自分类Dev

无法在新项目中创建ViewModel类的实例

来自分类Dev

房间中的SUM-无法在类ViewModel错误内创建实例-Java

来自分类Dev

RecyclerView.Adapter类Kotlin中无法获取ViewModel实例

来自分类Dev

Scala创建别名类型的实例

来自分类Dev

意外的行为创建类型的实例

来自分类Dev

为新类型创建实例

来自分类Dev

创建新的ViewModel实例时,视图状态保持不变

来自分类Dev

创建未知类型的实例

来自分类Dev

无法在 Fragment 中实例化 ViewModel

来自分类Dev

在 RecyclerView 中创建多个 ViewModel 实例

来自分类Dev

创建变量类型“T”的实例