Here is an example of how to create something both in XAML as well as code behind (C#). I see a lot of questions from people who know how to create controls in XAML but not programmatically. So, here we will create a ScatterView with a single ScatterViewItem and a SurfaceButton with a Click event handler.

XAML:

<Grid Background="{StaticResource WindowBackground}" Width="1024" Height="768">

    <s:ScatterView x:Name="SV">

        <s:ScatterViewItem Width="100" Height="100"

                           Background="White">

               

            <s:SurfaceButton Width="50" Height="50"

                             Content="GO!"

                             Click="SurfaceButton_Click" />

        </s:ScatterViewItem>

    </s:ScatterView>

</Grid>

Easy enough, right? But what if I asked you do do this programmatically? Would you know how to write the code to create those controls, set their properties, and set up the heiearchy correctly? If you don't then keep reading.

The SurfaceButton we created has an event handler for the Click event, SurfaceButton_Click. Lets write a method that will create an exact duplicate of the ScatterViewItem, its contents, and wire up the Click event so that it can do the same thing. In that method we will create a new ScatterViewItem and SurfaceButton control, set their properties, add some color just for fun, wire up the event handler, and set up the hierarchy. Something like this:

CS:

private void SurfaceButton_Click(object sender, RoutedEventArgs e)

{

    //create a new SVI and button control

    ScatterViewItem svi = new ScatterViewItem();

    SurfaceButton sb = new SurfaceButton();

 

    //set the width and height

    svi.Width = 100;

    svi.Height = 100;

    sb.Width = 50;

    sb.Height = 50;

 

    //generate a random color for the background, expanded for readability

    Random rand = new Random();

    byte red = (byte)(rand.Next(0, 255));

    byte blue = (byte)(rand.Next(0, 255));

    byte green = (byte)(rand.Next(0, 255));

 

    Color c = Color.FromRgb(red, blue, green);

    svi.Background = new SolidColorBrush(c);

 

    //add the event handler to the button

    sb.Click += new RoutedEventHandler(SurfaceButton_Click);

 

    //add the button text

    sb.Content = "GO!";

 

    //add the button to the SVI

    svi.Content = sb;

 

    //add the SVI to the ScatterView

    SV.Items.Add(svi);

}

Run the project and click on the button a few times. You should see a new SVI created each time you click on it. Now, click on the button on one of the newly created SVI's, the behavior should be the same.