将包装面板添加到堆栈面板中

时间:2014-03-21 08:35:09

标签: c# wpf

为什么这不起作用?堆栈面板具有默认设置按钮不应超出边界。

void AddWrapPanel() {

    WrapPanel myWrapPanel = new WrapPanel();
    myWrapPanel.Background = System.Windows.Media.Brushes.Azure;
    myWrapPanel.Orientation = Orientation.Horizontal;
    myWrapPanel.Width = 200;
    myWrapPanel.HorizontalAlignment = HorizontalAlignment.Left;
    myWrapPanel.VerticalAlignment = VerticalAlignment.Top;

    // Define 3 button elements. The last three buttons are sized at width 
    // of 75, so the forth button wraps to the next line.
    Button btn1 = new Button();
    btn1.Content = "Button 1";
    btn1.Width = 200;
    Button btn2 = new Button();
    btn2.Content = "Button 2";
    btn2.Width = 75;

    // Add the buttons to the parent WrapPanel using the Children.Add method.
    myWrapPanel.Children.Add(btn1);
    myWrapPanel.Children.Add(btn2);
    this.stackPanel1.Children.Add(myWrapPanel);
}

private void button1_Click(object sender, RoutedEventArgs e)
{
    AddWrapPanel();
}

这里是XAML

  <Window x:Class="AmpelThingy.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="349,276,0,0" Name="button1" VerticalAlignment="Top" Width="75" />
        <StackPanel Height="214" HorizontalAlignment="Left" Margin="32,33,0,0" Name="stackPanel1" VerticalAlignment="Top" Width="392" />
    </Grid>
</Window>

它是一个类似的问题,我不知道我能写些什么细节

1 个答案:

答案 0 :(得分:1)

在这里你已经创建了一个方法“button1_Click”但是WPF如何知道它何时应该实际调用它?因此,您必须将按钮单击事件挂钩到“button1_Click”方法。您可以使用Click =“button1_Click”属性来执行此操作。现在您的XAML将如下所示:

        <Grid>
            <Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="349,276,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
            <StackPanel Height="214" HorizontalAlignment="Left" Margin="32,33,0,0" Name="stackPanel1" VerticalAlignment="Top" Width="392" />
        </Grid>

希望这会对你有帮助..!