Wiring Events

You can wire events either through code or through XAML. Suppose you wish to display the contents of a TextBox called txtUserlD using the event handler shown in Listing 6-19.

Listing 6-19. Button Event Handler private void cmdOK_Click(object sender, RoutedEventArgs e) {


You can accomplish this through XAML by wiring the event handler by name to the Click property like this:

<Button Margin="99,0,104,106" Name="cmdOK" Height="23"

VerticalAlignment="Bottom" Click="cmdOK_Click">OK</Button>

Or you can accomplish it in code by assigning a delegate to the event handler:

cmdOK.Click += new RoutedEventHandler(this.cmdOK_Click);

This event-wiring approach is exactly the same as with Win and WebForms.

XAML does offer one additional possibility for storing source code and associating it with an event. You can store the source code in the XAML itself in a CDATA section using an x:Code directive element. CDATA sections are part of XML, not just XAML, and are used to inform the parser that the text contained within the section isn't XML markup and therefore shouldn't be interpreted as such. Here you can store a block of .NET source code that will compile at compile time, not at runtime like the examples shown in Chapter 2. When the XAML file is compiled, the code contained within the x:Code element is placed in a partial class in the Window1.g.cs file. This is a C# code file with suffix .g.cs, the g being short for "generated". This code can be embedded in the XAML as shown in Listing 6-20.

Listing 6-20. CDA TA Section

<Button Margin="86,122,91,117" Name="cmdCodeInXAML"

Click="cmdCodeInXAML_Click">Code In XAML</Button>

void cmdCodeInXAML_Click(object sender, RoutedEventArgs e) {

MessageBox.Show("You clicked me!");

0 0

Post a comment