C# Code In WPF XAML File

Here, we will learn how to write C# code in WPF XAML.

Step 1 Create WPF Window

  • Create new WPF window in WPF application.
  • Add a Button in the created window.
    1. <Window x:Class="DropBoxIntegration.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:DropBoxIntegration" mc:Ignorable="d" Title="MainWindow" Height="321" Width="1024" MinHeight="300" MinWidth="600">  
    2.     <Grid>  
    3.         <Button x:Name="button" Content="Button" HorizontalAlignment="Left" Margin="273,3,0,0" Grid.Row="3" VerticalAlignment="Top" Width="75" Height="17">  
    4.   
    5. </Button> </Grid>  
    6. </Window>  

Step 2 Messagebox popup on button click.

  • Add the below mentioned code as it is inside <button> tag.
  • Bind the Buttonclick event to the below event “Clicked”.
    1. <x:Code>  
    2.     <![CDATA[  
    3.   
    4. void Clicked(object sender, RoutedEventArgs e)  
    5. {  
    6.     MessageBox.Show("Hello World");  
    7. }  
    8. ]]>  
    9. </x:Code>  

  • The final status will be something like mentioned below.
    1. <Window x:Class="DropBoxIntegration.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:DropBoxIntegration" mc:Ignorable="d" Title="MainWindow" Height="321" Width="1024" MinHeight="300" MinWidth="600">  
    2.     <Grid>  
    3.         <Button x:Name="button" Content="Button" HorizontalAlignment="Left" Margin="273,3,0,0" Grid.Row="3" VerticalAlignment="Top" Width="75" Height="17" Click="Clicked">  
    4.   
    5. <x:Code>  
    6. <![CDATA[  
    7.    void Clicked(object sender, RoutedEventArgs e)  
    8.    {  
    9.       MessageBox.Show("Hello World");  
    10.    }  
    11. ]]>  
    12. </x:Code>  
    13.    </Button> </Grid>  
    14. </Window>  

That’s it. We are done. Try it yourself and see the result.

Ebook Download
View all
Learn
View all