这个问题几乎说明了一切.

我有一个窗口,并try 使用完整名称空间将DataContext设置为ViewModel,但我似乎做错了什么.

<Window x:Class="BuildAssistantUI.BuildAssistantWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    DataContext="BuildAssistantUI.ViewModels.MainViewModel">

推荐答案

除了其他人提供的解决方案(这是好的、正确的),还有一种方法可以在XAML中指定ViewModel,但仍然可以将特定的ViewModel与视图分离.当您想要编写独立的测试用例时,将它们分开是很有用的.

应用程序内.xaml:

<Application
    x:Class="BuildAssistantUI.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:BuildAssistantUI.ViewModels"
    StartupUri="MainWindow.xaml"
    >
    <Application.Resources>
        <local:MainViewModel x:Key="MainViewModel" />
    </Application.Resources>
</Application>

在MainWindow.xaml中:

<Window x:Class="BuildAssistantUI.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    DataContext="{StaticResource MainViewModel}"
    />

.net相关问答推荐

避免函数和其他对象之间的相互递归的模式?

.NET Async / Await:状态机如何知道何时继续执行?

System.IO.Directory.Exists 在 LINQ 语句中失败,但在 foreach 循环中没有

如何在选项卡中 Select Winforms NumericUpDown 中的所有文本?

为什么这个多态 C# 代码会打印它的功能?

AutoMapper 的替代品

是否可以像 WebView 一样在 Windows 窗体中嵌入 Gecko 或 Webkit?

C# 时间跨度毫秒与 TotalMilliseconds

使用 IIS Express 托管网站(临时)

如何删除只读文件?

Select 文件夹对话框 WPF

struct 中需要覆盖什么以确保平等正常运行?

如何在我的 C# 程序的面板中运行另一个应用程序?

Linq to SQL - 返回前 n 行

在 WPF DataGrid 中绑定 ComboBoxColumn 的 ItemsSource

C# (.NET) 设计缺陷

铸造:(NewType)与对象作为NewType

在 WPF 中设置 Tab 键顺序

在 .NET 中乘以时间跨度

如何在 ASP.NET MVC 中重定向到动态登录 URL