如何在 TabItem 加载时初始化 TabItem 内容?

How can I initialize TabItem content on TabItem load?

有没有办法在标签加载时初始化标签内容?我有一个问题,当创建 Tab 时它不会立即初始化它的组件。只有当我点击 Tab 时,内容才会显示。

<TabControl
        ItemsSource="{Binding Items}">
                <TabControl.ItemTemplate>
                    <DataTemplate>
                        <DockPanel>
                            <TextBlock Text="{Binding TabName}"><TextBlock.Background><SolidColorBrush /></TextBlock.Background></TextBlock>
                            <Button Name="btnDelete" DockPanel.Dock="Right" Margin="5,0,0,0" Padding="0"  CommandParameter="{Binding RelativeSource={RelativeSource AncestorType={x:Type TabItem}}, Path=Name}" BorderBrush="#00000000">
                                <Image Source="/WPF_AccApp;component/Images/11.gif" Height="11" Width="11"></Image>
                            </Button>
                            <DockPanel.Background>
                                <SolidColorBrush />
                            </DockPanel.Background>
                        </DockPanel>
                    </DataTemplate>
                </TabControl.ItemTemplate>
                <TabControl.ContentTemplate>
                    <DataTemplate>
                        <views:TabItemView />
                    </DataTemplate>
                </TabControl.ContentTemplate>
            </TabControl>

按钮点击事件

        private void AddInvoice_Click(object sender, RoutedEventArgs e)
    {
        count++;

        string s = string.Format("Tab {0}", count);
        mainViewModel.Items.Add(new ItemViewModel(s));
        this.DataContext = mainViewModel;
        if (count == 1)
        {
           //this is as work around
           // mainViewModel.Items.Add(new ItemViewModel(s));
           // mainViewModel.Items.RemoveAt(1);
        }

    }

找到解决方案https://social.msdn.microsoft.com/Forums/vstudio/en-US/8043441a-95bb-4f70-b64c-a76f89980068/tabcontrol-getting-the-work-done-in-viewmodel-when-selectionchanged?forum=wpf

您需要添加 Selected Tab Index 属性 并将其绑定到 TabControl