如何使用 DataContext 属性在 XAML 中的窗口上设置 ViewModel? [英] How do I set a ViewModel on a window in XAML using DataContext property?
问题描述
这个问题几乎说明了一切.
The question pretty much says it all.
我有一个窗口,并尝试使用完整的命名空间将 DataContext 设置为 ViewModel,但我似乎做错了什么.
I have a window, and have tried to set the DataContext using the full namespace to the ViewModel, but I seem to be doing something wrong.
<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.当您想编写隔离的测试用例时,将它们分开非常有用.
In addition to the solution that other people provided (which are good, and correct), there is a way to specify the ViewModel in XAML, yet still separate the specific ViewModel from the View. Separating them is useful for when you want to write isolated test cases.
在 App.xaml 中:
In App.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 中:
In 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}"
/>
这篇关于如何使用 DataContext 属性在 XAML 中的窗口上设置 ViewModel?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!