gpt4 book ai didi

c# - WPF 数据模板和自动创建的 viewModel 对象

转载 作者:行者123 更新时间:2023-12-03 10:58:50 25 4
gpt4 key购买 nike

我想在我的 WPF 应用程序中实现导航(使用 MVVM 模式)。
存在以下 ViewModel:

  • MainViewModel:包含功能区的应用程序的“框架”
  • ConsignorViewModel:一个“子” View ,必须显示在
    “框架”
  • RecipientViewModel:另一个“子” View ...

  • 为了让 WPF 决定必须在“框架”中显示哪个 View ,我使用 DataTemplates,在 App.xaml 中声明如下:
    <Application x:Class="MyProject.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:viewModels="clr-namespace:MyProject.ViewModels"
    xmlns:views="clr-namespace:MyProject"
    StartupUri="MainWindow.xaml">
    <Application.Resources>
    <BooleanToVisibilityConverter x:Key="BoolToVis"/>
    <DataTemplate DataType="{x:Type viewModels:ConsignorViewModel}">
    <views:ConsignorUC />
    </DataTemplate>
    <DataTemplate DataType="{x:Type viewModels:RecipientViewModel}">
    <views:RecipientUC />
    </DataTemplate>
    </Application.Resources>
    </Application>

    我的 MainViewModel 有一个 ViewModel 类型的属性“CurrentViewModel”(我的基类)。 ConsignorViewModel 和 RecipientViewModel 是 ViewModel。

    ConsignorViewModel 的 View 是“用户控件”(窗口不适用于功能区)。
    <UserControl x:Class="MyProject.ConsignorUC"
    ...>
    <UserControl.DataContext>
    <local:ConsignorViewModel />
    </UserControl.DataContext>
    <Grid>
    ...
    <TextBox Name="searchterm" Margin="10,10,1,1" TextWrapping="Wrap" Text="{Binding SearchTerm, UpdateSourceTrigger=PropertyChanged}" Grid.Column="1" />
    ...
    </Grid>
    </Grid>
    </UserControl>

    双向数据绑定(bind)在 subview 中不起作用。我错过了什么?说ConsignorViewModel必须绑定(bind)到用户控件是不是错了?

    更新
    我找到了问题,但没有找到解决方案:
    启动应用程序时,会创建一个新的 MainViewModel 对象。因此我说
    currentViewModel = new ConsignorViewModel();

    现在我的 subview 是ConsignorUC。当创建一个新的 ConsignorUC 时,会创建一个新的 ConsignorViewModel 对象。所以我必须有不同的 ConsignorViewModel 对象,但我应该只有一个。

    最佳答案

    您的问题实际上在这里:

    <UserControl.DataContext>
    <local:ConsignorViewModel />
    </UserControl.DataContext>

    您显式地创建一个新的 View 模型并将其分配给 DataContext该 View 创建时的 View 属性。

    只需将其替换为类似
    <UserControl 
    x:Class="MyProject.ConsignorUC"
    DataContext = "{Binding DataContext.CurrentViewModel, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}"/>

    使用这种方法,您可以设置 DataContext您的 child 对 CurrentViewModel 的值(value)的看法窗口 View 模型的属性。

    关于c# - WPF 数据模板和自动创建的 viewModel 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27579731/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com