Mastering Visual Studio 2017
上QQ阅读APP看书,第一时间看更新

Working with inline code in XAML pages

You can write inline programming code (C# or VB.NET) within the XAML page, using the x:Code directive and must be surrounded by <![CDATA[...]]> to escape the contents for XML. This can interact within the same XAML page:

<Window x:Class="MyWpfApplication.MainWindow" 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
  Title="Main Window" Height="350" Width="525"> 
  <Grid> 
    <Button Click="Button_Click" Content="Click Here" /> 
    <x:Code> 
      <![CDATA[ 
        void Button_Click(object sender, RoutedEventArgs e) 
        { 
          // event implementation 
        }  
      ]]> 
    </x:Code> 
  </Grid> 
</Window> 

Try to avoid using the inline code in the XAML page, as it violates the separation between the designer and the code behind. Also, other language-specific programming features are not supported in inline coding.