如何在XAML中实例化DataContext对象

29

我希望能够在XAML中创建DataContext对象的实例,而不是在代码中创建并以编程方式设置DataContext属性。

主要原因是我不需要从外部访问创建的对象,也不想为设置DataContext而编写代码。

我相信我曾经在某个地方读到过如何在XAML中实例化DataContext对象,但我在任何通常的地方都找不到它...

4个回答

34

在您的DataContext所属的任何命名空间中添加一个XML命名空间,在窗口资源中创建一个实例,并将DataContext设置为该资源:

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

这个在.NET Framework 4.5中能用吗?我尝试了这段代码,但它显示...“未找到类型'local:MyViewModel'。请确认您没有丢失任何程序集并且所有引用的程序集都已构建。” - Rafaf Tahsin
@RafafTahsin 你确定你的命名空间写对了吗?另外,如果你将引用的类型添加到项目中但尚未构建,WPF设计器可能会有些混乱。你试过构建了吗? - Randolpho
如果您也在使用ResourceDictionary,则local:MyViewModel应该放在字典中(但任何MergedDictionary)。 - xvan

28

您可以直接在XAML中为整个窗口指定:

<Window 
    ... xmlns definitions ...
>
   <Window.DataContext>
        <local:CustomViewModel />
   </Window.DataContext>
</Window>

这将在使用本地别名的命名空间中创建一个名为"CustomViewModel"的视图模型,并直接将其作为窗口的DataContext。


16

假设有如下代码:

public abstract class BaseView { }
public class RuntimeView : BaseView { }
public class DesigntimeView : BaseView { }

试试这个:

<Page.DataContext>
    <local:RuntimeView />
</Page.DataContext>
<d:Page.DataContext>
    <local:DesigntimeView />
</d:Page.DataContext>
<ListBox ItemsSource="{Binding}" />

祝你好运!


1
+1 是因为这样可以同时显示运行时和设计时,而且不使用 x:Key,而是直接将 DataContext 放在其所属的元素中。 - stijn

0
如果您需要将DataContext设置为相同的控件类:
    <Window x:Class="TabControl.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"        
            xmlns:local="clr-namespace:TabControl"
            Title="MainWindow" Height="350" Width="525"
            DataContext="{Binding RelativeSource={RelativeSource Self}}"        
            >
</Window>

使用RelativeSource绑定。

或者只需

     <Window x:Class="TabControl.MainWindow"
                xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"        
                xmlns:local="clr-namespace:TabControl"
                Title="MainWindow" Height="350" Width="525"                        
                >
<Window.DataContext>
< new instance of any viewModel here....>
</Window.DataContext>
    </Window>

如果想要分配一个不同于自身类的实例。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接