简体   繁体   English

将WPF xaml绑定到ViewModel而不构造它

[英]Binding WPF xaml to a ViewModel without constructing it

My WPF app doesn't use an app.xaml. 我的WPF应用程序不使用app.xaml。 I'm using MVVM, and construct the view and the viewmodel separately. 我正在使用MVVM,并分别构造视图和viewmodel。 I then pass the ViewModel to the View constructor and set the datacontext there. 然后,我将ViewModel传递给View构造函数,并在那里设置datacontext。

I'd like to have Visual Studio be able to understand the viewmodel's properties for context clicking and such, but not have it construct its own DataContext when the view is set. 我希望Visual Studio能够了解上下文模型等视图模型的属性,但是在设置视图时不希望它构造自己的DataContext。

When I do this, it forces me to have a default constructor for MainViewModel, and then it calls that VM constructor when I construct the View. 当我这样做时,它迫使我为MainViewModel拥有一个默认的构造函数,然后在构造View时调用该VM构造函数。

<Window x:Class="Kraken.CopFeed.Windows.MainFeedView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:Windows="clr-namespace:MyProgram.MainApp.WpfWindows"
        mc:Ignorable="d"
        Title="Main App" Height="321.557" Width="652.922">

    <Window.DataContext>
        <Windows:MainViewModel />
    </Window.DataContext>

How can I keep my existing implementation of constructing the V and VM separately, but get the XAML editor in Visual STudio to know of my ViewModel that will (eventually) be set as the data context? 如何保留现有的分别构造V和VM的实现,但是如何在Visual STudio中使XAML编辑器知道将(最终)设置为数据上下文的ViewModel?

I think you should be able to do this with d:DesignInstance , as in this question . 我认为您应该能够使用d:DesignInstance做到这一点,就像这个问题一样

<Window
    ...etc...
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    mc:Ignorable="d"

    d:DataContext="{d:DesignInstance Type=MyViewModelNamespace:MyViewModel}"
    >

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM