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. </Button> </Grid>
    5. </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. void Clicked(object sender, RoutedEventArgs e)
    4. {
    5. MessageBox.Show("Hello World");
    6. }
    7. ]]>
    8. </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. <x:Code>
    5. <![CDATA[
    6. void Clicked(object sender, RoutedEventArgs e)
    7. {
    8. MessageBox.Show("Hello World");
    9. }
    10. ]]>
    11. </x:Code>
    12. </Button> </Grid>
    13. </Window>

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