如何设置使用DataContext属性在XAML窗口的视图模型?视图、如何设置、属性、模型

2023-09-02 01:24:50 作者:我会在星期八把你忘记

现在的问题pretty的多少说明了一切。

我有一个窗口,并尝试使用完整的命名空间的视图模型设置的DataContext,但我好像做错了什么。

 <窗​​口x:类=BuildAssistantUI.BuildAssistantWindow
    的xmlns =htt​​p://schemas.microsoft.com/winfx/2006/xaml/$p$psentation
    的xmlns:X =htt​​p://schemas.microsoft.com/winfx/2006/xaml
    的DataContext =BuildAssistantUI.ViewModels.MainViewModel>
 

解决方案

在除了解决方案,其他人提供的(这是好的,正确的),有一种方法来指定视图模型在XAML中,但仍然分开从查看特定视图模型。将它们分开是当你想要编写独立的测试案例有用的。

MVVM模式C 实现步骤

在App.xaml中:

 <应用
    X:类=BuildAssistantUI.App
    的xmlns =htt​​p://schemas.microsoft.com/winfx/2006/xaml/$p$psentation
    的xmlns:X =htt​​p://schemas.microsoft.com/winfx/2006/xaml
    XMLNS:地方=CLR的命名空间:BuildAssistantUI
    的StartupUri =MainWindow.xaml
    >
    < Application.Resources>
        <地方:MainViewModel X:关键=MainViewModel/>
    < /Application.Resources>
< /用途>
 

在MainWindow.xaml:

 <窗​​口x:类=BuildAssistantUI.MainWindow
    的xmlns =htt​​p://schemas.microsoft.com/winfx/2006/xaml/$p$psentation
    的xmlns:X =htt​​p://schemas.microsoft.com/winfx/2006/xaml
    的DataContext ={的StaticResource MainViewModel}
    />
 

The question pretty much says it all.

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">

解决方案

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.

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"
    StartupUri="MainWindow.xaml"
    >
    <Application.Resources>
        <local:MainViewModel x:Key="MainViewModel" />
    </Application.Resources>
</Application>

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}"
    />