动态创建 2 个具有不同内容 wpf 的选项卡

本文关键字:wpf 选项 创建 动态 | 更新日期: 2023-09-27 18:34:08

以下代码在单击按钮时创建 2 个选项卡,但不显示任何内容。我还在学习这个,想知道错误是什么。

代码隐藏

public void button2_Click(object sender, RoutedEventArgs e)
{
    popUp1.IsOpen = false;
    Canvas canvas4 = new Canvas();
    ScrollViewer viewer4 = new ScrollViewer();
    viewer4.Content = canvas4;
    string txtfl = File.ReadAllText(textBox1.Text);
    TextBlock txbl1 = new TextBlock();
    txbl1.Text = txtfl;
    canvas4.Children.Add(txbl1);
    TabItem newTab1 = new TabItem();
    newTab1.Header = "Text File";
    newTab1.Content = viewer4;
    tabctrl1.Items.Add(newTab1);
    tabctrl1.SelectedItem = newTab1;
    Brush br = new SolidColorBrush(Colors.White);
    Canvas canvas2 = new Canvas();
    canvas2.Background = br;
    ScrollViewer viewer2 = new ScrollViewer();
    viewer2.Content = canvas2;
    TabItem newTab2 = new TabItem();
    newTab2.Header = "Test";
    newTab2.Content = viewer2;
    tabctrl1.Items.Add(newTab2);
}

选项卡控件是使用 XAML 创建的

XAML

<Window ... >
    <Grid>
        <Popup Name="popUp1" Width="500" Height="300" Placement="Center" IsEnabled="False" IsOpen="False">
            <Canvas x:Name="myCanvas1" Width="500"  Height="300" Visibility="Visible">
                <Button Content="Button" Height="38" HorizontalAlignment="Left" Margin="12,71,0,0" Name="button1" VerticalAlignment="Top" Width="151" Click="button2_Click" />                            
            </Canvas>
        </Popup>
        <TabControl Name="tabctrl1" Width="1345" Height="28" Margin="0,24,0,0" HorizontalAlignment="Left" VerticalAlignment="Top" BorderThickness="2">
            <TabControl.Background>
                <LinearGradientBrush EndPoint="0,1" StartPoint="0,0">
                    <GradientStop Color="#FF3A60AD" Offset="0.528"/>
                    <GradientStop Color="#FF6A85D8" Offset="0.01"/>
                </LinearGradientBrush>
            </TabControl.Background>                   
        </TabControl>
    </Grid>
</Window>

动态创建 2 个具有不同内容 wpf 的选项卡

嗨,您的代码似乎不起作用的原因是选项卡控件的高度设置为 28。

尝试将其更改为 280,然后您应该能够看到内容。

  <TabControl Name="tabctrl1" Width="1345" Height="280" Margin="0,24,0,0" HorizontalAlignment="Left" VerticalAlignment="Top" BorderThickness="2">