如何设置使用DataContext属性在XAML窗口的视图模型? [英] How do I set a ViewModel on a window in XAML using DataContext property?

查看:418
本文介绍了如何设置使用DataContext属性在XAML窗口的视图模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在的问题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中,但仍然分开从查看特定视图模型。将它们分开是当你想要编写独立的测试案例有用的。

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

这篇关于如何设置使用DataContext属性在XAML窗口的视图模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆