使用不同的内容wpf动态创建2个选项卡

时间:2012-05-15 10:27:07

标签: c# .net wpf wpf-controls

以下代码在单击按钮时创建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);
}

TabControl是使用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>

1 个答案:

答案 0 :(得分:0)

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

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

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