如何实例化XAML DataContext对象 [英] How to instantiate DataContext object in XAML

查看:387
本文介绍了如何实例化XAML DataContext对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够创建的DataContext 对象在XAML我的WPF的StartupUri窗口的实例,而不是创建它的代码,然后设置的DataContext 属性programmaticly。

I want to be able to create an instance of the DataContext object for my WPF StartupUri window in XAML, as opposed to creating it code and then setting the DataContext property programmaticly.

主要的原因是我并不需要访问外部创建的对象,我不希望有写代码的背后只是设置的DataContext

The main reason is I don't need to access the object created externally and I don't want to have to write code behind just for setting the DataContext.

我敢肯定,我在什么地方如何阅读实例在XAML的的DataContext 的对象,但在任何平常的地方...

I'm sure I've read somewhere how to instantiate the DataContext object in XAML but I can't find it in any of the usual places...

推荐答案

您添加一个XML命名空间的任何空间的DataContext的生活,创建的窗口资源的它的实例,并在DataContext设置为资源:

You add an XML namespace for whatever namespace your DataContext lives in, create an instance of it in the Window Resources and set the DataContext to that resource:

<Window x:Class="WpfApplication4.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication4"
    Title="Window1" Height="300" Width="300">
    <Window.Resources>
        <local:MyViewModel x:Key="MyViewModel"/>
    </Window.Resources>
    <Grid DataContext="{StaticResource MyViewModel}">

    </Grid>
</Window>

这篇关于如何实例化XAML DataContext对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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