【问题标题】:How to properly pass parameters between modelView and View for the datacontext如何在模型视图和视图之间正确传递数据上下文的参数
【发布时间】:2016-02-13 00:41:09
【问题描述】:

我有以下几点: - 类 AccountViewModel:BaseViewModel - AccountView.xaml

我正在努力将参数传递给 ModelView。

在主窗口中,我将它们绑定在一起:

<DataTemplate DataType="{x:Type local:AccountViewModel}">
     <local:AccountView />
</DataTemplate>

在 mainWindowViewModel 中,我有一个操作来显示 Account 视图:

ChangeViewModel(new AccountViewModel(new DateTime(2016, 2, 06), new DateTime(2016, 2, 15)))

如您所见,AccountViewModel 的构造函数有 2 个参数,即 2 个日期时间。

然后在 AccountView 中,我尝试通过以下方式创建 DataContext:

<UserControl.DataContext>
    <ObjectDataProvider ObjectType="local:AccountViewModel"
    xmlns:sys="clr-namespace:System;assembly=mscorlib">
        <ObjectDataProvider.ConstructorParameters>
            <sys:DateTime></sys:DateTime>
            <sys:DateTime></sys:DateTime>
        </ObjectDataProvider.ConstructorParameters>
    </ObjectDataProvider>
</UserControl.DataContext>

无论我做什么,它都会创建另一个 AccountViewModel 实例。我不希望这样,我希望这个 AccountView 继续使用我在上面显示的命令中创建的 AccountViewModel,但我也想使用绑定功能。如果可能的话,我宁愿尽量避免使用后面的代码。

我怎样才能做到这一点?

【问题讨论】:

    标签: wpf mvvm datacontext


    【解决方案1】:

    您无需在ViewModel 上创建额外的对象。当您的 View 由您的 DataTemplate DataType 定义时。它将自动传递给您的视图。

    See this answer to understand DataContext here

    从您的View 中删除您的以下代码并检查DataContext,它将是local:AccountViewModel:

    <UserControl.DataContext>
    <ObjectDataProvider ObjectType="local:AccountViewModel"
    xmlns:sys="clr-namespace:System;assembly=mscorlib">
        <ObjectDataProvider.ConstructorParameters>
            <sys:DateTime></sys:DateTime>
            <sys:DateTime></sys:DateTime>
        </ObjectDataProvider.ConstructorParameters>
    </ObjectDataProvider>
    

    【讨论】:

    • 我实际上是在一些不需要修复的东西上浪费了时间......非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-07
    • 1970-01-01
    • 2012-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多