gpt4 book ai didi

wpf - 如何在 WPF MVVM 中动态设置 View 的 DataContext

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

所以我对 WPF 和 MVVM 比较陌生,我在这里遇到了 TabControl 的问题,并试图在选项卡之间切换时保留数据。基本上,我在 View 中有一个 TabControl,并且 TabItems 根据用户交互动态加载和删除。每个 TabItem 都是一个 UserControl,它是具有自己的 View 模型的自己的 View 。

Every time a TabItem is removed (not always just going to another tab, sometimes the tabs are actually removed and recreated) I am saving the instance of its viewmodel and preserving the data but I'm having trouble getting that data back when the tab is重新创建。我正在使用数据模板来创建 TabItems

<DataTemplate x:Key="MyView" DataType="{x:Type vm:MyViewModel}">
<uc:MyView />
</DataTemplate>

并在 TabControl 中引用它。
<TabControl ItemsSource="{Binding ViewModelList, Mode=TwoWay}" 
ContentTemplate="{StaticResource MyView}"
ItemTemplate="{StaticResource MyHeader}"
SelectedIndex="{Binding SelectedTabIndex, Mode=TwoWay}" />

就所有内容的显示方式而言,一切都有效,但我每次都会得到一个新的空白版本的 UserControl。设置为 ViewModelList 的 itemssource 正是它听起来的样子,我的 View 模型实例列表,用于保存每个选项卡的状态,以便可以重新创建它。这里的问题是,这里使用的 DataTemplate 方法并没有真正给我一种方法来将我的 View 模型数据绑定(bind)到每次创建新 TabItem 时正在创建的 View 的新实例。

我没有使用 MVVMLight 或 Prism,但我确实有一个自定义的 EventAggregator,我在这里尝试过使用。我遇到的问题是在正确的时间将数据获取到正确的 View 模型实例。我认为我的部分问题是 MyViews datacontext 在其代码隐藏构造函数中设置为 MyViewModel 的新实例,并且它覆盖了我尝试传入的任何其他内容......

我只是不知道如何解决这个问题。我为这个冗长的问题道歉,但我想尝试涵盖所有内容。如果有人需要更多信息,请告诉我,提前谢谢!

最佳答案

嗯,不太确定,但值得一试。我想,如果你修改你的 DataTemplate

<DataTemplate x:Key="MyView" DataType="{x:Type vm:MyViewModel}">
<uc:MyView DataContext={Binding} />
</DataTemplate>

它可能会起作用。试试看,让我知道。

好吧,这很奇怪。来自 MSDN

  • Items - Gets the collection used to generate the content of the ItemsControl. (Inherited from ItemsControl.)

[...]

  • ItemsSource - Gets or sets a collection used to generate the content of the ItemsControl. (Inherited from ItemsControl.)


您可能想尝试使用 Items反而。

关于wpf - 如何在 WPF MVVM 中动态设置 View 的 DataContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16941147/

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