使用该窗口上的按钮关闭以编程方式创建的窗口

时间:2011-05-04 21:06:22

标签: c# wpf

在后面的代码中,我创建了一个新窗口,当我单击主窗体上的按钮时弹出该窗口。在窗口我有一个图像和一些文本与一个按钮关闭窗口。在代码背后我怎么能只关闭那个窗口?我继续创建一个btn.Click += new RoutedEventHandler(btn_Click);,但我需要能够在窗口中传递一些如何在该函数中看到它。有没有办法检查是否单击按钮我在哪里实际创建窗口和按钮所以我可以关闭该窗口?

Show_Dialog1_Click是主窗体上的按钮。

这是窗口和按钮的代码

private void Show_Dialog1_Click(object sender, RoutedEventArgs e)
{


    Window wnd = new Window();
    Grid grid = new Grid();
    wnd.Height = 450;
    wnd.Width = 450;
    wnd.MinHeight = 450;
    wnd.MinWidth = 450;
    wnd.MaxHeight = 450;
    wnd.MaxWidth = 450;

    grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(30) });
    grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(30) });
    grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(300) });
    grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(40) });
    grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(100) });
    grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
    wnd.Content = grid;
    BitmapImage src = new BitmapImage();
    src.BeginInit();
    src.UriSource = new Uri("jimmy.jpg", UriKind.Relative);
    src.EndInit();
    Image i = new Image();
    i.Source = src;
    i.Stretch = Stretch.Uniform;


    Button btn = new Button();
    btn.Content = "Close";
    btn.Height =  30;
    btn.Width = 150;
    btn.VerticalAlignment = VerticalAlignment.Bottom;
    btn.HorizontalAlignment = HorizontalAlignment.Center;
    //btn.Click += new RoutedEventHandler(btn_Click);


    Label lblDialog = new Label();


    lblDialog.Content = "Sample Dialog Box";
    lblDialog.FontWeight = FontWeights.Bold;
    lblDialog.Foreground = Brushes.Black;
    lblDialog.Background = Brushes.LightBlue;

    Label lblexample = new Label();
    lblexample.Content = "This is an example of a standard dialog box component.";
    lblexample.FontSize = 12;
    Grid.SetRow(lblDialog, 0);
    Grid.SetRow(lblexample, 1);
    Grid.SetRow(i, 2);
    Grid.SetRow(btn,3);
    grid.Children.Add(lblDialog);
    grid.Children.Add(lblexample);
    grid.Children.Add(i);
    grid.Children.Add(btn);


    wnd.Owner = this;
    wnd.ShowDialog();

}

1 个答案:

答案 0 :(得分:4)

btn.Click += (q,w) => wnd.Close();