الأربعاء، 1 يونيو 2011

Code Inside XAML


XAML actually supports “code inside” in addition to code behind (somewhat like in ASP.NET).
This can be done with the Code keyword in the XAML language namespace, as follows:
<Window x:Class="WpfApplication3.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:my="clr-namespace:WpfApplication3"
        Title="MainWindow" Height="350" Width="525" xmlns:shared="http://schemas.actiprosoftware.com/winfx/xaml/shared" xmlns:navigation="http://schemas.actiprosoftware.com/winfx/xaml/navigation" xmlns:docking="http://schemas.actiprosoftware.com/winfx/xaml/docking" xmlns:editors="http://schemas.actiprosoftware.com/winfx/xaml/editors" xmlns:ribbon="http://schemas.actiprosoftware.com/winfx/xaml/ribbon">
    <Grid>
        <Button Click="button_Click">OKButton>
        <x:Code>
           
void button_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
]]>
        x:Code>
    Grid>
Window>

When such a XAML file is compiled, the contents inside the x:Code element get plopped inside the partial class in the .g.cs file. Note that the procedural language is not specified in the XAML file; it is determined by the project containing this file.
Wrapping the code in isn’t required, but it avoids the need to escape less than signs as <, and ampersands as &. That’s because CDATA sections are ignored by XML parsers, whereas anything else is processed as XML. (The tradeoff is that you must avoid using ]]>  anywhere in the code, because that terminates the CDATA section!)
Of course, there’s no good reason to pollute your XAML files with this “code inside” feature.
Besides making the division between UI and logic messier, loose XAML pages don’t support it and Visual Studio doesn’t show syntax coloring

0 التعليقات: