Now we are going to add code to MainPage.xaml
to display a SpinningControl
object. When you open the MainPage.xaml
file, you will see the following XAML code created for you by Visual Studio:
<UserControl x:Class="SpinningControlSample.MainPage" 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:i="http://schemas.microsoft.com/expression/2010/interactivity" xmlns:se="http://schemas.microsoft.com/expression/2010/interactions" xmlns:SpinningControlSample="clr-namespace:SpinningControlSample" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="400"> <Grid x:Name="LayoutRoot" Background="White"> </Grid> </UserControl>
Let's modify this class to display our SpinningControl
object as a rectangle rotated by an angle specified by its RotationAngle
property:
<UserControl x:Class="SpinningControlSample.MainPage" ... d:DesignHeight="300" d:DesignWidth="400"> <Grid x:Name="LayoutRoot" Background="White"> <!--Dependency Property RotationAngle is referred to within XAML in exactly the same way as the usual property (as in the line below)--> <SpinningControlSample:SpinningControl x:Name="TheSpinningControl" RotationAngle="45"> <SpinningControlSample:SpinningControl.Template> <!-- SpinningControl's template is set to create a visual representation for the control. --> <ControlTemplate TargetType="SpinningControlSample:SpinningControl"> <Rectangle Fill="Orange" Width="100" Height="30" RenderTransformOrigin="0.5,0.5"> <Rectangle.RenderTransform> <!-- We use "Binding" to connect RotateTransform's Angle property to the RotationAngle Dependency Property. --> <RotateTransform Angle="{Binding Path=RotationAngle, Mode=OneWay, RelativeSource= {RelativeSource Mode=TemplatedParent}}" /> </Rectangle.RenderTransform> </Rectangle> </ControlTemplate> </SpinningControlSample:SpinningControl.Template> </SpinningControlSample:SpinningControl> </Grid> </UserControl>
If you build and run the SpinningControlSample
solution, you will get a 45 degree rotated orange rectangle displayed in a browser window as shown in the following screenshot:
Note that we defined the template for our lookless control inline (see the <SpinningControlSample:SpinningControl.Template>
tag).