使用我的类的 ViewModel 指定资源时发生错误:
<Window x:Class="KTM.TouristsListWnd"
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:KTM"
mc:Ignorable="d"
Title="TouristsList" Height="388.102" Width="1001.393" Loaded="Window_Loaded">
<Window.DataContext>
<!-- ошибка воникает здесь -->
<local:TouristsListViewModel />
</Window.DataContext>
尽管该类在范围内(公共)?
public class TouristsListViewModel
UPD:类构造函数:
public TouristsListViewModel()
{
try {
conn.Open();
MySqlCommand cmd = new MySqlCommand("SELECT * FROM tourmanager.tourists;", conn);
MySqlDataAdapter adp = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds);
foreach (DataRow dr in ds.Tables[0].Rows) {
_tourists.Add(new Tourist((int)dr["id"], (string)dr["firstname"], (string)dr["secondname"],
(string)dr["patronymic"], (string)dr["passport"], (string)dr["sex"]));
}
} catch (MySqlException ex) {
throw new Exception("", ex);
} finally {
conn.Close();
}
}
问题是这样的。程序编译正常,但在Intellisense(即可视化编辑器)中出现错误。
XAML 编辑器尝试创建一个实例
TouristsListWnd以绘制它。当然,在这样做时,它也会尝试创建一个实例TouristsListViewModel,因为它是 XAML 的一部分。但在设计时,构造函数似乎并没有触发。一个简单的解决方案是检查我们是否在设计器中运行。为此,您可以使用以下构造:
在构造函数的开头。
另外:请注意属性声明及其初始化
实际上也是构造函数的一部分,如果我们在设计器中禁用它,我们需要将这个初始化移动到一个后检查点。你得到这个:
请注意,在 VM 对象构造函数中执行长时间操作是不好的 - 这会减慢 UI 线程。因此,让我们尝试将表的读取移动到一个单独的线程中。你会得到这样的东西:
我将从我自己的角度补充(我认为用更简单的语言)。如果您根据数据库中的查询在 VM 构造函数中创建对象(此查询或查询的对象是通过 ConfigurationManager 类形成的),则会发生此错误。为避免错误,您需要将对数据库的所有调用隐藏在作者指出的条件后面:
我没有从数据库中获取数据,而是在对象初始值设定项的必填字段(或属性)中手动输入了一些值,这应该足以方便地在 xaml 中呈现设计。