XAML elements can send messages when certain events occur. These event messages give you the opportunity to take some action in response to the event. You put your code to respond to the event in an event handler method. One of the most common events in many apps is a user clicking a Button.
Let's create an event handler for your button's Click event. The event handler will get the user's name from the
nameInput
TextBox control and use it to output a greeting to the greetingOutput
TextBlock. Using events that work for touch, mouse, and pen input :
What event should you handle? Because they can run on a variety of devices, design your Windows Store apps with touch input in mind. Your app must also be able to handle input from a mouse or a stylus. Fortunately, events such as Click and DoubleTapped are device-independent. If you're familiar with Microsoft .NET programming, you might have seen separate events for mouse, touch, and stylus input, like MouseMove, TouchMove, and StylusMove. In Windows Store apps, these separate events are replaced with a single PointerMoved event that works equally well for touch, mouse, and stylus input.To add an event handler
- In XAML or design view, select the "Say Hello" Button that you added to MainPage.xaml.
- In the Properties Window, click the Events button (
).
- Find the Click event at the top of the event list. In the text box for the event, type the name of the function that handles the Click event. For this example, type "Button_Click".
- Press Enter. The event handler method is created and opened in the code
editor so you can add code that's executed when the event occurs. . In the XAML editor, the XAML for the Button is updated to declare the Click event handler like this.
<Button Content="Say "Hello"" Click="Button_Click"/>
- Add code to the event handler that you created in the code behind page. In the event handler, retrieve the user's name from the
nameInput
TextBox control and use it to create a greeting. Use thegreetingOutput
TextBlock to display the result.private void Button_Click(object sender, RoutedEventArgs e) { greetingOutput.Text = "Hello, " + nameInput.Text + "!"; }
- Press F5 to build and run the app. When you enter your name in the text
box and click the button, the app displays a personalized greeting.
No comments:
Post a Comment