如果WPF主窗口中有四个内容相同的TabItem(一个View,一个ViewModel),如何告诉View它属于哪个TabItem?

8zzbczxx  于 2023-08-07  发布在  其他
关注(0)|答案(1)|浏览(174)

在探索/学习WPF/MVVM的下一步中,我使用了一个带有一个TabControl和四个TabItem的MainWindow。每个选项卡都有相同的内容,一组四个CheckBox定义在一个View中,因此也定义在一个ViewModel中。正如我从各种构造函数中的各种Debug.WriteLine语句中看到的,一个View被示例化了四次,ViewModel也被示例化了四次。
Four TabItems, same content
到目前为止一切顺利,但每个选项卡的数据应该存储在后端(尚未确定),所以我需要通知View示例,从而通知ViewModel示例它们属于哪个TagItem。以便可以单独存储每个TabItem的选中CheckBox。
我确实尝试使用ObjectDataProvider text向OneView构造函数传递参数,但无法使其工作。有什么建议吗?
``

  1. <Window x:Class="FourTabsOneView.MainWindow"
  2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  5. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  6. xmlns:vws="clr-namespace:FourTabsOneView.Views"
  7. mc:Ignorable="d"
  8. Title="MainWindow" Height="200" Width="400">
  9. <TabControl x:Name="tControl">
  10. <TabItem x:Name="One" Header="TabOne" Width="80">
  11. <vws:OneView/>
  12. </TabItem>
  13. <TabItem x:Name="Two" Header="TabTwo" Width="80">
  14. <vws:OneView/>
  15. </TabItem>
  16. <TabItem x:Name="Three" Header="TabThree" Width="80">
  17. <vws:OneView/>
  18. </TabItem>
  19. <TabItem x:Name="Four" Header="TabFour" Width="80">
  20. <vws:OneView/>
  21. </TabItem>
  22. </TabControl>
  23. </Window>
  24. <UserControl x:Class="FourTabsOneView.Views.OneView"
  25. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  26. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  27. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  28. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  29. xmlns:vms="clr-namespace:FourTabsOneView.ViewModels"
  30. mc:Ignorable="d"
  31. d:DesignHeight="200" d:DesignWidth="400">
  32. <UserControl.DataContext>
  33. <vms:OneViewModel />
  34. </UserControl.DataContext>
  35. <StackPanel Orientation="Vertical">
  36. <CheckBox x:Name="cb01" IsThreeState="False" Height="30"
  37. IsChecked="{Binding CB01}"
  38. Content="CheckBox A" />
  39. <CheckBox x:Name="cb02" IsThreeState="False" Height="30"
  40. IsChecked="{Binding CB02}"
  41. Content="CheckBox B" />
  42. <CheckBox x:Name="cb03" IsThreeState="False" Height="30"
  43. IsChecked="{Binding CB03}"
  44. Content="CheckBox C" />
  45. <CheckBox x:Name="cb04" IsThreeState="False" Height="30"
  46. IsChecked="{Binding CB04}"
  47. Content="CheckBox D" />
  48. </StackPanel>
  49. </UserControl>
fdbelqdn

fdbelqdn1#

实现这一点的惯用方法是在视图模型中创建一个可观察的集合,该集合包含所需的每个子视图模型,然后将该集合绑定到TabControlItemsSource属性。这将为集合中的每个元素填充一个选项卡控件。
故事的其余部分很简单,只是模板。你有你的ContentTemplate属性,它定义了孩子应该如何看(你的用户控件)和你的ItemTemplate,它定义了头应该如何看(一个文本块绑定到你孩子的VM中的Name属性)。
另外,不要试图手动更改用户控件的数据上下文,因为框架已经正确处理了它。

相关问题