简体   繁体   中英

Adding Wrap Panel in to a Stack Panel

Why does this no work? The Stack Panel has default settings Buttons shouldn't be out of border.

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();
}

here the 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>

its a simle problem i dont know what more details i can write

Here you have created a method "button1_Click" but how does WPF know when it should actuallly call it? So, you have to hook buttons click event to "button1_Click" method. You can do it using Click="button1_Click" property. Now your XAML will look like :

        <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>

Hope this will help you..!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM