user249375
user249375

Reputation:

close a programatically created window with a button on that window

In the code behind i created a new window that pops up when i click a button on the main form. On the window i have an image and some text with a button to close the window. In the code behind how can i close only that window? I went ahead and created a btn.Click += new RoutedEventHandler(btn_Click); but i need to be able to pass in the window some how for it to be seen in that function. Is there a way to check if the button is clicked where i create the window and button pragmatically so i can close that window?

Show_Dialog1_Click is button on the main form.

here is the code for the window and button

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

}

Upvotes: 0

Views: 285

Answers (1)

Poma
Poma

Reputation: 8474

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

Upvotes: 4

Related Questions