简体   繁体   中英

C#WPF hello world button_click

I am a beginner , I make my first application. want to do a hello 'name'.I do this :

namespace MyApp
{
  public partial class MainPage : PhoneApplicationPage
  {
    public MainPage()
    {
        InitializeComponent();

        Title = "Page1";
        Height = 500;
        Width = 500;

        TextBox NameTxtBox = new TextBox();
        NameTxtBox.Width = 300;

        Button Button1 = new Button();
        Button1.Content = "ok";

        TextBlock TxtBlock = new TextBlock();
        TxtBlock.Width = 300;

        StackPanel MyStackPanel = new StackPanel();
        MyStackPanel.Margin = new Thickness(10);
        MyStackPanel.Height = 500;
        MyStackPanel.Width = 500;
        MyStackPanel.Children.Add(NameTxtBox);
        MyStackPanel.Children.Add(ValidateButton);
        MyStackPanel.Children.Add(TxtBlock);

        Content = MyStackPanel;
    }
  }
}

in textbox write his name, and when the button is clicked , the text displayed in textblock would hello 'name' (name = name written in textbox).

I can't use privade void button_click (...) in public MainPage(), and after, i don't have access to textblock.text

You need an event handler to handle the click of the button.

The event handler is a function that will be triggered each time the user presses the button.

The handler looks like this:

public void Button1_OnClick(object sender,EventArgs e)
{
    //Place Code here
}

The name of the handler is just a convention, you can name it however you like. Then you need to register this event handler to the appropriate event, in this case to the Button1.OnClick() event. You can do so in many ways, you can use the properties tab of the Visual Studio IDE or you can simply type the following from within your Main function:

Button1.OnClick += Button1_OnClick

The above code segment links the handler with the actual event. An event can have multiple handlers.

An event is a list of methods that are called when the event is fired.

For more information check this tutorial from MSDN Events And Delegates

Currently your "ok" button doesn't do anything.

You can use graphical XAML designer, or if you wish to keep dynamic control adding (like currently), you have to attach an Event Handler on the Click event of your button.

In this event handler, you'll have to write the behavior you want to have when the button will be clicked.

This example will certainly be helpful : http://www.stackoverflow.com/a/5929779/461444

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