Vitor Cunha
Vitor Cunha

Reputation: 11

C# WPF Textbox click Event

I create a stackpanel, and put some controls and 1 of these is a textbox, programaticly. How can i create an event that, when i click on textbox i delete the stackpanel and everything inside? Here is my code...

        System.Windows.Controls.StackPanel Defesa = new StackPanel();
        Defesa.Height = 120;
        Defesa.Width = 140;
        Panel_DE.Children.Add(Defesa);
        Defesa.Background = new 

        SolidColorBrush((Color)ColorConverter.
        ConvertFromString("#FF000000"));
        Defesa.Margin = new Thickness(20, 0, 0, 0);
        Ellipse Foto = new Ellipse();
        Foto.Height = 80;
        Foto.Width = 80;
        Foto.StrokeThickness = 2;
        SolidColorBrush borda = new SolidColorBrush();
        borda.Color = Colors.White; ;
        Foto.Stroke = borda;
        Defesa.Children.Add(Foto);
        ImageBrush camera = new ImageBrush();
        camera.ImageSource = new BitmapImage(new 
        Uri(@"C:\Users\Vitor\documents\visual studio 2013\Projects\Manager 
        Treinador\Manager Treinador\Icons\photo-camera w.png"));
        Foto.Fill = camera;
        System.Windows.Controls.TextBlock Nome_def = new TextBlock();
        Nome_def.Text = def_name;
        Nome_def.Foreground = new 
        SolidColorBrush((Color)ColorConverter.ConvertFromString
        ("#FFF9F4F4"));
        Nome_def.HorizontalAlignment = HorizontalAlignment.Center;
        Defesa.Children.Add(Nome_def);
        System.Windows.Controls.StackPanel Panel = new StackPanel();
        Panel.Orientation = Orientation.Horizontal;
        Defesa.Children.Add(Panel);
        System.Windows.Controls.TextBlock But_Delet = new TextBlock();
        But_Delet.Text = "X";
        But_Delet.FontWeight = FontWeights.Bold;
        But_Delet.Foreground = new 
        SolidColorBrush((Color)ColorConverter.ConvertFromString
        ("#FFF90707"));
        Panel.Children.Add(But_Delet);
        But_Delet.HorizontalAlignment = HorizontalAlignment.Left;
        But_Delet.Cursor = Cursors.Hand;

But_Delete is the text box that i want to remove all...

Thanks

Upvotes: 0

Views: 2111

Answers (1)

Jeff
Jeff

Reputation: 654

Since a TextBlock does not have a click event, you will need to simulate this by using OnPreviewMouseDown event. To do this:

add this to the end of your code:

But_Delet.PreviewMouseDown += ButDeletOnPreviewMouseDown;

Then add this event handler:

private void ButDeletOnPreviewMouseDown(object sender, MouseButtonEventArgs e)
{
    Panel_DE.Children.Remove(Defesa);
}

However, if there is a chance you will need to restore these controls, it would better to hide them using this event handler instead:

private void ButDeletOnPreviewMouseDown(object sender, MouseButtonEventArgs e)
{
    Defesa.Visibility = Visibility.Hidden;
}

Upvotes: 0

Related Questions