c# - 将 WPF xaml 绑定(bind)到 ViewModel 而不构建它

标签 c# wpf xaml mvvm

我的 WPF 应用程序不使用 app.xaml。我正在使用 MVVM,并分别构建 View 和 View 模型。然后,我将 ViewModel 传递给 View 构造函数并在那里设置数据上下文。

我希望 Visual Studio 能够理解 View 模型的上下文单击属性等,但在设置 View 时不让它构造自己的 DataContext。

当我这样做时,它会强制我拥有 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>

如何保留分别构建 V 和 VM 的现有实现,同时让 Visual STudio 中的 XAML 编辑器了解我的 ViewModel(最终)将设置为数据上下文?

最佳答案

我认为您应该能够使用 d:DesignInstance 来完成此操作,如 this question 中所示。

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

关于c# - 将 WPF xaml 绑定(bind)到 ViewModel 而不构建它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41108343/

相关文章:

c# - 取消异步调用 (IAsyncResult)

c# - 类型 'UserControl' 不支持直接内容

wpf - 使用WPF对象到另一个 'punch'洞?

.net - 从 WPF 应用程序启动 metro 应用程序(相机)

c# - 对话框有未请求的额外空间

c# - WPF - 在 Extended WPF Toolkit 中自定义 MessageBox 的样式

c# - Xamarin - 我如何在类外使用列表

c# - 不明确的类型名称

c# - 如何在单独的线程中运行计时器?

c# - 如何在 Windows Phone 8 中异步 append 文件