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

问题描述 投票:0回答:0

探索/学习 WPF/MVVM 的下一步将我带到一个带有 TabControl 和四个 TabItem 的主窗口。每个选项卡都有相同的内容,在一个视图中定义一组四个复选框,因此在一个视图模型中定义。 正如我从各种构造函数中的各种 Debug.WriteLine 语句中看到的,一个 View 被实例化了四次,ViewModel 也被实例化了四次。

Four TabItems, same content

到目前为止一切顺利,但每个选项卡的数据应该存储在后端(尚未确定),因此我需要通知 View 实例,从而通知 ViewModel 实例它们所属的 TagItem。这样每个TabItem的勾选的CheckBox就可以单独存储。

我确实尝试使用 ObjectDataProvider text 将参数传递给 OneView 构造函数,但无法使其工作。有什么建议吗?


<Window x:Class="FourTabsOneView.MainWindow"
    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:vws="clr-namespace:FourTabsOneView.Views"
    mc:Ignorable="d"
    Title="MainWindow" Height="200" Width="400">
    <TabControl x:Name="tControl">
        <TabItem x:Name="One" Header="TabOne" Width="80">
            <vws:OneView/>
        </TabItem>

        <TabItem x:Name="Two" Header="TabTwo" Width="80">
            <vws:OneView/>
        </TabItem>

        <TabItem x:Name="Three" Header="TabThree" Width="80">
            <vws:OneView/>
        </TabItem>

        <TabItem x:Name="Four" Header="TabFour" Width="80">
            <vws:OneView/>
        </TabItem>
    </TabControl>
</Window>

<UserControl x:Class="FourTabsOneView.Views.OneView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:vms="clr-namespace:FourTabsOneView.ViewModels"
             mc:Ignorable="d" 
             d:DesignHeight="200" d:DesignWidth="400">

    <UserControl.DataContext>
        <vms:OneViewModel />
    </UserControl.DataContext>
    
    <StackPanel Orientation="Vertical">
        <CheckBox x:Name="cb01" IsThreeState="False" Height="30" 
                          IsChecked="{Binding CB01}"
                          Content="CheckBox A" />
        <CheckBox x:Name="cb02" IsThreeState="False" Height="30"
                          IsChecked="{Binding CB02}"
                          Content="CheckBox B" />
        <CheckBox x:Name="cb03" IsThreeState="False" Height="30"
                          IsChecked="{Binding CB03}"
                          Content="CheckBox C" />
        <CheckBox x:Name="cb04" IsThreeState="False" Height="30"
                          IsChecked="{Binding CB04}"
                          Content="CheckBox D" />
    </StackPanel>
</UserControl>
c# wpf mvvm tabcontrol tabitem
© www.soinside.com 2019 - 2024. All rights reserved.