top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Understanding XAML Schemas And Namespace Declarations?

+3 votes
628 views

XAML is actually a flavor of XML, so in order to work with XAML, we need to follow its schema. Schema is like an agreement between both the producer and consumer of XML, so they can work together in case you want to read that schema.

Whenever you create a new UWP Application in Visual Studio, you will find some namespaces in the designer code of XAML. UWP stands for Universal Windows Platform. Go to solution explorer and open MainPage.xaml. You'll find the following lines of code in the tag of <page----></page> of your application. These are different schema and namespaces used in UWP applications. Now we're going to explore these namespaces one by one.

XMAL

In the very first line you can find your class name which is in fact your application name with MainPage. Below it you'll find few namespaces like:

  • :x
  • :local
  • :d
  • :mc

These are the namespaces that are used for different purposes. Le's explain each one-by-one --  and one more thing before starting, that URL which you're watching here are not URLs, in fact. They are UR, which stands for Uniform Resource Indicator. URI is used to define a namespace that we can use further in our document of the app.

  1. xmlns = " http:/schemas.microsoft.com/winfx/2006/xaml/presentation "

    This schema defines all UI ( User Interface ) components like button, textblock, etc.
     
  2. xmlns : x = " http://schemas.microsoft.com/winfx/2006/xaml "

    All of the rules of XAML in general are defined at this schema. From rules you can assume that rules which have to be followed while writing UI in XAML.
     
  3. xmlns : local = " using: --- name of application --- "

    This is a local namespace. You can reference your own local classes here by using this namespace in application. 
     
  4. xmlns : d = "http://schemas.microsoft.com/expression/blend/2008 "
     
  5. xmlns : mc = " http://schemas.openxmlformats.org/markup-compatibility/2006 "

    xmlns : d and xmlns : mc are the schemas used to represent the design view of application. Design view is the designer area of application.
     
  6. mc : Ignorable = " d "

    If you want to ignore some namespace on runtime, put that namespace in double quotes as here "d " will be ignored on runtime that has been defined already on the fourth line. This option exists here because of xmlns : mc namespace.

That is all. Please provide feedback so that I'll improve my writing and be able to share further stuff better.

posted Feb 18, 2016 by Jdk

  Promote This Article
Facebook Share Button Twitter Share Button LinkedIn Share Button


Related Articles

In this article you will learn how to create and use a CustomResource in XAML.

 

  1. Open a new Visual C# windows project.
     
  2. Add a new class named say CustomResourceTest.cs in the project folder.

    CustomResourceTest.cs
     
  3. Derive this class from CustomXamlResourceLoader Class(Case sensitive) like below:

    CustomXamlResourceLoader Class
     
  4. You will get a Namespace not found error. Resolve it by using Windows.UI.Xaml.Resources Namespace.

    Windows.UI.Xaml.Resources
     
  5. Override the GetResource Member of the parent class as below. Use the intellisense to select the member.

    getresource

    getresource1
     
  6. Replace the Code inside the GetResource Method as: (this is just a simple example). We are returning a text. We plan to show this text inside a TextBlock’s Text Property.

    TextBlock
     
  7. Inside the MainPage.cs . Add the following line of code inside the MainPage Constructor to reference the CustomResouceTest.cs Class from the Page’s XAML.

    MainPage

    Correct the NameSpace not found error by resolving it.
     
  8. Now go to the MainPage.xaml Page and Add a TextBlock as follows. Notice the Text property of the TextBlock.

    MainPage.xaml
     
  9. This results in the following output when you save, build and run the project.

    run
     
  10. What is happening here?
     
    • We created a CustomResourceClass where we inherited the Class called CustomXamlResourceLoader.
    • We override the GetResourceProperty. Don’t focus on the parameters of this method for now.
    • We replaced the code inside this method by simply returning a text.
    • To access this CustomResource from XAML we have to define the CustomXamlResourceLoader. Current property to the new instance of the Class we created. We have to do this inside the Constructor of the Codebehind page where we want to use the CustomResource.
    • We then simply assigned the value of the Text property of the textblock to the CustomResource as seen on Step 8.

Example 2:

  1. Now we will try a different example where we want to display the Text of the TextBlock based on the value we pass on. Change the text of the Mainpage.xaml as:

    Mainpage.xaml 2
     
  2. The 'sayHello' string is passed as a string to the CusomResourceTest.cs class as ResourceID parameter of the overridden class. This will be more clear as you see in the next step.
     
  3. In the CustomResourceTest.cs class , change the code as follows:

    CustomResourceTest.cs2
     
  4. The thing to understand is how we pass the ResourceID from the Text Property of the TextBlock. It is passed as the resourceID parameter. So, based on the ResourceID, we return the appropriate text we want to display on the output screen.
     
  5. So now we get output as.
  6. If we change the text property as sayByeBye.

    sayByeBye
     
  7. We get the following output:
     
READ MORE

it's about separating data from layout. So, let's try binding some data to a ListView:

using System;
using System.Collections.Generic;
using System.Windows;

namespace WpfTutorialSamples.ListView_control
{
        public partial class ListViewDataBindingSample : Window
        {
                public ListViewDataBindingSample()
                {
                        InitializeComponent();
                        List<User> items = new List<User>();
                        items.Add(new User() { Name = "John Doe", Age = 42 });
                        items.Add(new User() { Name = "Jane Doe", Age = 39 });
                        items.Add(new User() { Name = "Sammy Doe", Age = 13 });
                        lvDataBinding.ItemsSource = items;
                }
        }

        public class User
        {
                public string Name { get; set; }

                public int Age { get; set; }
        }
}

We populate a list of our own User objects, each user having a name and an age. The data binding process happens automatically as soon as we assign the list to the ItemsSource property of the ListView, but the result is a bit discouraging:

A simple ListView control, using data binding

Each user is represented by their type name in the ListView. This is to be expected, because .NET doesn't have a clue about how you want your data to be displayed, so it just calls the ToString() method on each object and uses that to represent the item.

We can use that to our advantage and override the ToString() method, to get a more meaningful output. Try replacing the User class with this version:

public class User
{
        public string Name { get; set; }

        public int Age { get; set; }

        public override string ToString()
        {
                return this.Name + ", " + this.Age + " years old";
        }
}

A simple ListView control, using data binding and a ToString method on the source object

This is a much more user friendly display and will do just fine in some cases, but relying on a simple string is not that flexible. Perhaps you want a part of the text to be bold or another color? Perhaps you want an image? Fortunately, WPF makes all of this very simple using templates.

ListView with an ItemTemplate

WPF is all about templating, so specifying a data template for the ListView is very easy. In this example, we'll do a bunch of custom formatting in each item, just to show you how flexible this makes the WPF ListView.

Download sample

<Window x:Class="WpfTutorialSamples.ListView_control.ListViewItemTemplateSample"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="ListViewItemTemplateSample" Height="150" Width="350">
    <Grid>
                <ListView Margin="10" Name="lvDataBinding">
                        <ListView.ItemTemplate>
                                <DataTemplate>
                                        <WrapPanel>
                                                <TextBlock Text="Name: " />
                                                <TextBlock Text="{Binding Name}" FontWeight="Bold" />
                                                <TextBlock Text=", " />
                                                <TextBlock Text="Age: " />
                                                <TextBlock Text="{Binding Age}" FontWeight="Bold" />
                                                <TextBlock Text=" (" />
                                                <TextBlock Text="{Binding Mail}" TextDecorations="Underline" Foreground="Blue" Cursor="Hand" />
                                                <TextBlock Text=")" />
                                        </WrapPanel>
                                </DataTemplate>
                        </ListView.ItemTemplate>
                </ListView>
        </Grid>
</Window>

 

READ MORE

I am building a website in XAML (Silverlight) and trying to put prototype samples together to see what can be done in Silverlight and what obstacles will I face in building samples that can easily be done in ASP.NET 2.0. One piece of this was to create an animated banner that shows some ads and give text animations such as changing colors, rotation, and size.

In a graphics designer, you create layers and frames and give them a time interval to load a different layer to create an animated graphics. Fortunately, this functionality is built-in in WPF and XAML. Now, I don't have to create different layers or frames. I can simply create a text and apply animation or transformation on the text and WPF will take care for me. 

I have a banner looks like Figure 1.

 

AnimatedBanImg1.jpg
Figure 1. Initial banner

As you can see from Figure 1, I have four text blocks loaded in the banner and two of them are with a gradient background. I would apply four different animations on these four text blocks. I would change the gradient background of first text block, change the foreground color of second text block, change the width of third text block, and rotate the fourth text block. The running banner will look like Figure 2 and repeat this behavior indefinitely.

 

AnimatedBanImg2.jpg

Figure 2. Animated text banner

The magic begins within the Storyboard tag of XAML. Within the Storyboard tag, we can use animations such as double animation, color animation, point animation, or transformation.

<TextBlock.Triggers>

      <EventTrigger RoutedEvent="FrameworkElement.Loaded">

            <BeginStoryboard>

                  <Storyboard>

                                         

                  </Storyboard>

            </BeginStoryboard>

      </EventTrigger>

</TextBlock.Triggers>

The DoubleAnimation tag is used to apply transparency on controls. The following code shows the syntax of the DoubleAnimation. The TargetName is the name of the control such as a TextBlock. The From and To attributes is the range for transparency range between 1.0 and 0.0 where 1.0 is fully opaque and 0.0 is fully transparent.  The RepeatBehavior is Forever means the animation will repeat forever.

<DoubleAnimation

      Storyboard.TargetName="TB"                                 Storyboard.TargetProperty="Opacity"

      From="1.0" To="0.0" Duration="0:0:5"

      AutoReverse="True" RepeatBehavior="Forever" />

The following code shows how to user color animation using the ColorAnimation tag, which takes TargetName as name of the brush and TargetProperty as Color. The From and To attributes are starting and end colors.

<ColorAnimation

Storyboard.TargetName="SB"

Storyboard.TargetProperty="Color"

From="Pink" To="SteelBlue" Duration="0:0:5"

AutoReverse="True" RepeatBehavior="Forever" />

The following code usage double animation to set the transformation angle of the text box to rotate a text block.

<DoubleAnimation

Storyboard.TargetName="MyRT"

      Storyboard.TargetProperty="(RotateTransform.Angle)"

      From="0.0" To="360" Duration="0:0:10"

RepeatBehavior="Forever" />

Download the attached XAML file for more details and complete XAML code.  

Here is a listing of complete XAML code:

<Window

      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

      x:Class="AnimatedBanner.Window1"

      x:Name="Window"

      Title="Window1"

      Width="396" Height="492"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"mc:Ignorable="d" Foreground="#FFF15151" SnapsToDevicePixels="True" >

 

      <Grid x:Name="LayoutRoot">

            <Rectangle Margin="66,42,152,20" Stroke="#FF000000" RadiusX="0"RadiusY="0">

                  <Rectangle.Fill>

                        <LinearGradientBrush x:Name="MRGB" EndPoint="0.5,1"StartPoint="0.5,0">

                              <GradientStop Color="#FF000000" Offset="0"/>

                              <GradientStop Color="#FF5E0805" Offset="0.478"/>

                        </LinearGradientBrush>

                  </Rectangle.Fill>            

            </Rectangle>

           

      <TextBlock x:Name="TB" Margin="75,49,161,0" FontFamily="Book Antiqua"FontSize="24" FontWeight="Bold" TextWrapping="Wrap" Foreground="#FFF9F4F4"TextAlignment="Center" Height="56" VerticalAlignment="Top" ><TextBlock.Background>

                        <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">

                              <GradientStop Color="#FF000000" Offset="0"/>

                              <GradientStop Color="#FFD600FF" Offset="1"/>

                        </LinearGradientBrush>

                  </TextBlock.Background>

                  <TextBlock.Triggers>

                        <EventTrigger RoutedEvent="FrameworkElement.Loaded">

                              <BeginStoryboard>

                                    <Storyboard>

                                          <DoubleAnimation

                                                Storyboard.TargetName="TB"

                                                Storyboard.TargetProperty="Opacity"

                                                From="1.0" To="0.0"Duration="0:0:5"

                                                AutoReverse="True"RepeatBehavior="Forever" />

                                    </Storyboard>

                              </BeginStoryboard>

                        </EventTrigger>

                  </TextBlock.Triggers><Run FontFamily="Cambria" FontSize="20"Text="Need help on a .NET Project? "/></TextBlock>

            <TextBlock x:Name="TB2" Margin="75,225,161,131" FontFamily="Book Antiqua" FontSize="24" FontWeight="Bold" TextWrapping="Wrap" Foreground="#FFF9F4F4"TextAlignment="Center"><TextBlock.Background>

                        <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">

                              <GradientStop Color="#FF000000" Offset="0"/>

                              <GradientStop Color="#FF00FF4D" Offset="1"/>

                        </LinearGradientBrush>

                  </TextBlock.Background>

                  <LineBreak/><Run FontFamily="Cambria" FontSize="20"Foreground="#FF97ECC3" Text="Let our experts help you."/>

                  <TextBlock.Triggers>

                        <EventTrigger RoutedEvent="FrameworkElement.Loaded">

                              <BeginStoryboard>

                                    <Storyboard/>

                              </BeginStoryboard>

                        </EventTrigger>

                  </TextBlock.Triggers>

                  </TextBlock>

     

           

            <!-- Color Animation Sample. Changes color from Pink to SteelBlue -->

            <TextBlock

              x:Name="TB4"

              Margin="75,120,161,0" FontSize="16" FontWeight="Bold"VerticalAlignment="Top"

              Height="100" Text="Silverlight, C#, ASP.NET, WPF, WCF"TextWrapping="WrapWithOverflow" TextAlignment="Center">

              <TextBlock.Foreground>

                <SolidColorBrush x:Name="SB" Color="Pink" />

              </TextBlock.Foreground>

 

              <!-- Animates the text block's color. -->

              <TextBlock.Triggers>

                <EventTrigger RoutedEvent="FrameworkElement.Loaded">

                  <BeginStoryboard>

                    <Storyboard>

                        <!-- Use ColorAnimation with TargetProperty as Color and TargetName as brush being used

                        to draw the text -->

                      <ColorAnimation

                        Storyboard.TargetName="SB"

                        Storyboard.TargetProperty="Color"

                        From="Pink" To="SteelBlue" Duration="0:0:5"

                        AutoReverse="True" RepeatBehavior="Forever" />

                    </Storyboard>

                  </BeginStoryboard>

                </EventTrigger>

              </TextBlock.Triggers>

            </TextBlock>

 

 

            <!-- Text Rotation Sample -->

            <TextBlock

              x:Name="TB5"

              Margin="97,0,183,41"

              FontSize="18" FontWeight="Bold" Foreground="Green"VerticalAlignment="Bottom" Height="60"><TextBlock.RenderTransform>

                <RotateTransform x:Name="MyRT" Angle="0" CenterX="30"CenterY="25"/>

              </TextBlock.RenderTransform><!-- Animates the text block's rotation. --><TextBlock.Triggers>

                <EventTrigger RoutedEvent="FrameworkElement.Loaded">

                  <BeginStoryboard>

                    <Storyboard>

                        <!-- Use DoubleAnimation with TargetProperty as RotateTransform.Angle

                              and TargetName as name of the RotateTransform being used to rotate the text -->

                      <DoubleAnimation

                        Storyboard.TargetName="MyRT"

                        Storyboard.TargetProperty="(RotateTransform.Angle)"

                        From="0.0" To="360" Duration="0:0:10"

                        RepeatBehavior="Forever" />

                    </Storyboard>

                  </BeginStoryboard>

                </EventTrigger>

              </TextBlock.Triggers><Run FontSize="20" Text="Contact Us"/></TextBlock>

           

            <!-- Author TextBlok -->

     

      </Grid>

</Window>

READ MORE

While analyzing some controls used for touch devices I found this effective and easy logic for touch control and slow finishing action after touch leaves. Normally in touch devices we like to have control of an application with very smooth touch interaction. We also expect some slow finish of the action, like if we tap and wipe a control then it will move some distance and stay. So I found this logic to do that in an effective manner.

Platform support this approach

  • WPF
  • Windows Stores (WinRT)
  • Windows Phones 8 

Concept behind the approach

In my logic I have handled the manipulation of the data to the control. Using the manipulation of the data, I reset the matrix value of the control as desired. For slow finishing, I used a timer that enables the control for slower and smooth finishing actions after touch leaves.

XAML Code snippet behind the approach

<Button x:Class="TouchApplication.SmoothestTouchControl"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

mc:Ignorable="d"

d:DesignHeight="300" d:DesignWidth="300">

  <Grid>

  </Grid>

</Button>

<Window x:Class="TouchApplication.MainWindow"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

Title="MainWindow" Height="350" Width="525"

xmlns:local="clr-namespace:WpfApplication8">

  <Grid >

    <local:SmoothestTouchControl IsManipulationEnabled="True"

    RenderTransform="0.9 0 0 0.9 100 100" />

 

    <local:SmoothestTouchControl IsManipulationEnabled="True"

    RenderTransform="0.9 0 0 0.9 100 100" />

 

    <local:SmoothestTouchControl IsManipulationEnabled="True"

    RenderTransform="0.9 0 0 0.9 100 100" />

 

    <local:SmoothestTouchControl IsManipulationEnabled="True"

    RenderTransform="0.9 0 0 0.9 100 100" />

 

    <local:SmoothestTouchControl IsManipulationEnabled="True"

    RenderTransform="0.9 0 0 0.9 100 100" /

  </Grid>

</Window>

C# code snippet behind the approach
 

// Use required name space  using System;

using System.Linq;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Input;

using System.Windows.Media;

 

namespace TouchApplication

{

    /// Interaction logic for SmoothestTouchControl.xaml

 

    public partial class SmoothestTouchControl : Button

    {

        int i = 0; // Iteration count for slower animation to end

        UIElement uiElement = null; // contains current control

        MatrixTransform matrixTransform = null; // contains Matrix transform

        Matrix uiElementMatrix = new Matrix(); // contains Matrix of the UIElement

        ManipulationDelta manipulationDelta = null; // contains data of Manipulation

        Point centerPoint = new Point(); // contains center point of the element

        System.Windows.Forms.Timer smoother = new System.Windows.Forms.Timer(); // Animater that slow down the action after touch leave

        public SmoothestTouchControl()

        {

            smoother.Interval = 1; // Inverval for animater

            smoother.Tick += smoother_Tick; // hook event to animation

        }

        // override manupulation starting to reset the Z order to get the current touched UI element a top element

        protected override void OnManipulationStarting(ManipulationStartingEventArgs args)

        {

            args.ManipulationContainer = App.Current.MainWindow; // Get the parent window

 

            var frameworkElement = args.Source as FrameworkElement; // Get the current touched element

 

            var panel = frameworkElement.Parent as Panel; // Get parent element to have the children collection

 

            for (int i = 0; i < panel.Children.Count; i++) // Iterate the children collection to reset the Z order

            {

                Panel.SetZIndex(panel.Children[i], panel.Children[i] == frameworkElement ? panel.Children.Count : i);

            }

            args.Handled = true; // Get handled true

 

            base.OnManipulationStarting(args); // Call base for original action

        }

        // override manipulation delta for transform actions

        protected override void OnManipulationDelta(ManipulationDeltaEventArgs args)

        {

            uiElement = args.Source as UIElement; // Get the current touched element

            matrixTransform = uiElement.RenderTransform as MatrixTransform; // Get MatrixTransform of the element

            uiElementMatrix = matrixTransform.Matrix; // Get Matrix of the element

            manipulationDelta = args.DeltaManipulation; // Get delta manipulation of the touch action

            centerPoint = args.ManipulationOrigin; // Get center point of the manipulation

 

            uiElementMatrix.RotateAt(manipulationDelta.Rotation, centerPoint.X, centerPoint.Y); // Rotate the ccontrol acccording to manipulation

            uiElementMatrix.ScaleAt(manipulationDelta.Scale.X, manipulationDelta.Scale.Y, centerPoint.X, centerPoint.Y);// Scale the ccontrol acccording to manipulation

            uiElementMatrix.Translate(manipulationDelta.Translation.X, manipulationDelta.Translation.Y); // Move the ccontrol acccording to manipulation

 

            matrixTransform.Matrix = uiElementMatrix; // Reset the updated matrix to the element matrix

            args.Handled = true; // Get handled true

            base.OnManipulationDelta(args); // Call base for original action

        }

        // override manipulation completed to start slower finish of the touch action

        protected override void OnManipulationCompleted(ManipulationCompletedEventArgs e)

        {

            base.OnManipulationCompleted(e); // Call base for original action

            smoother.Interval = 1; // reset the interval of the slower finish action

            i = 10; // Reset the iterator of the slower finish

            smoother.Start(); // Start animation for slower finish

        }

 

        // slowe finish animater logic

        void smoother_Tick(object sender, EventArgs e)

        {

            i--; // for slow finish action

 

            smoother.Interval = smoother.Interval + 2; // increase interval for integrated slow finish

 

            if (smoother.Interval > 25) // Check for dezire interval

                smoother.Stop(); // Stop the animation

 

            if (manipulationDelta.Rotation != 0) // Check if the control atually in rotation

            {

                uiElementMatrix.RotateAt(manipulationDelta.Rotation - (i > 0 ? i : 1), centerPoint.X, centerPoint.Y); // keep rotation using iterated value

            }

            uiElementMatrix.Translate(manipulationDelta.Translation.X - (i > 0 ? i : 0), manipulationDelta.Translation.Y - (i > 0 ? i : 0)); // keep moving using iterated value

            matrixTransform.Matrix = uiElementMatrix; // reset the updated matrix to the element matrix  

        } 

    }

}

READ MORE

We can use the Arc XAML element to draw arcs in XAML. Besides drawing arcs using the Arc element, we can also use the ArcSegment element. The ArcSegment is useful when an arc becomes a part of a graphics path or a larger geometric object.

 

In this article, we will see how to use the ArcSegment to draw arcs in XAML and WPF.

 

The ArcSegment object represents an elliptical arc between two points. The ArcSegment class has the five properties Point, Size, SweepDirection, IsLargeArc and RotationAngle. 

 

  • The Point property represents the endpoints of an arc. 
  • The Size property represents the x and y radiuses of an arc. 
  • The SweepDirection property specifies whether an arc sweep direction is clock wise or counter clock wise. 
  • The IsLargeArc property returns true if an arc is greater than 180 degrees. 
  • The RotationAngle property represents the angle by which an ellipse is rotated about the x-axis.

 

 

The following figure provided by the MSDN documentation shows these property values and their results.

Graphics-Arc.jpg

<ArcSegment Size="300,50" RotationAngle="30" 
            IsLargeArc="True" SweepDirection="CounterClockwise"  Point="200,100" />

A Path object is used to draw an arc by setting a PathGeomerty as Path.Data. The following code snippet creates a Path and sets a ArcSegment as a part of PathFigure.Segments.

<Path Stroke="Black" StrokeThickness="1">
    <Path.Data>
        <PathGeometry>
            <PathGeometry.Figures>
                <PathFigureCollection>
                    <PathFigure StartPoint="0,100">
                        <PathFigure.Segments>
                            <PathSegmentCollection>
                                <ArcSegment Size="300,50" RotationAngle="30"
                                            IsLargeArc="True"
                                            SweepDirection="CounterClockwise"
                                            Point="200,100" />
                            </PathSegmentCollection>
                        </PathFigure.Segments>
                    </PathFigure>
                </PathFigureCollection>
            </PathGeometry.Figures>
        </PathGeometry>
    </Path.Data>
</Path>

The output looks like Figure 1.

 

ArcSegment-1.jpg

Figure 1

We can paint an arc by simply painting the path using the Fill method. The following code snippet has changes in it from the previous code that fills a path. 

<Path Stroke="Black" StrokeThickness="1" Fill="Yellow">

The new output looks like Figure 2.

 

ArcSegment-Filled.jpg

Figure 2

The following code snippet creates an arc segment shown in Figure 2 dynamically.

private void CreateArcSegment()
{
    PathFigure pthFigure = new PathFigure();
    pthFigure.StartPoint = new Point(0, 100); 

    ArcSegment arcSeg = new ArcSegment();
    arcSeg.Point = new Point(200, 100);
    arcSeg.Size = new Size(300,50);
    arcSeg.IsLargeArc = true;
    arcSeg.SweepDirection = SweepDirection.Counterclockwise;
    arcSeg.RotationAngle = 30;   

    PathSegmentCollection myPathSegmentCollection = new PathSegmentCollection();
    myPathSegmentCollection.Add(arcSeg); 

    pthFigure.Segments = myPathSegmentCollection; 

    PathFigureCollection pthFigureCollection = new PathFigureCollection();
    pthFigureCollection.Add(pthFigure); 

    PathGeometry pthGeometry = new PathGeometry();
    pthGeometry.Figures = pthFigureCollection; 

    Path arcPath = new Path();
    arcPath.Stroke = new SolidColorBrush(Colors.Black);
    arcPath.StrokeThickness = 1;
    arcPath.Data = pthGeometry;
    arcPath.Fill = new SolidColorBrush(Colors.Yellow); 

    LayoutRoot.Children.Add(arcPath);
}

 

READ MORE

In this article, I will try to make a representation of the Grid object witch is directly derived from the Panel abstract class and we can say that is a flexible area that contains rows and columns, it plays a role of container in a given WPF window. The grid could be found in the PresentationFramework assembly. The grid control could be used to create a complex layout that gives to the application an attractive and ergonomic look. So let's discover how to configure it using XAML in this part and in second part I will illustrate how to perform the same task using the code behind, I mean C#.

At first look, when a new WPF application is defined, we have the impression that there is not controls but the window one, even if the "<Grid></Grid>" tags are presents, and the first question that one can ask is where are the grid lines if it is a grid really? 

 

Figure 1

I tell you ok try this code:

<Grid ShowGridLines="True">

        <Grid.RowDefinitions>

            <RowDefinition></RowDefinition>

            <RowDefinition></RowDefinition>

            <RowDefinition></RowDefinition>

        </Grid.RowDefinitions>

        <Grid.ColumnDefinitions>

            <ColumnDefinition></ColumnDefinition>

            <ColumnDefinition></ColumnDefinition>

            <ColumnDefinition></ColumnDefinition>

        </Grid.ColumnDefinitions>       

    </Grid>

I use the <Grid.RowDefinitions> to define a collection of rows and a<Grid.ColumnDefinitions> to define columns collection. In the other hand I use<RowDefinition> to define a row element within the grid control and <ColumnDefinition> to define a column element, and then I set ShowGridLines property to true, it is very important in order to render columns and rows visible. The result will be as follows:

Figure 2

The columns and rows definition mode could be, namely star, Auto or Pixel.

The Star definition

It means that the related size could be expressed as weighted proportion of available space, for example if a size of a given first row is double of a second given row size, then the first one will receive two units of the entire grid size, meanwhile, the second one will have one unit as size. Rows and columns sizes are expressed by this symbol * that represents a unit of size. The XAML code sample illustrates how to define a size based on star definition.

<Grid ShowGridLines="True" >

        <Grid.RowDefinitions>

            <RowDefinition></RowDefinition>

            <RowDefinition></RowDefinition>

            <RowDefinition></RowDefinition>

        </Grid.RowDefinitions>

        <Grid.ColumnDefinitions>

            <ColumnDefinition Width="2*"></ColumnDefinition>

            <ColumnDefinition></ColumnDefinition>

            <ColumnDefinition></ColumnDefinition>

        </Grid.ColumnDefinitions>       

    </Grid>

The result of the above code is:

Figure 3

The above code sets the first column width as double of the reset of the columns.

The Pixel definition

It means that the size is defined in terms of pixels such as in the ASP applications. This bellow code illustrate how to define a dimension of a given column or row based on pixels

<Grid ShowGridLines="True" >

        <Grid.RowDefinitions>

            <RowDefinition></RowDefinition>

            <RowDefinition></RowDefinition>

            <RowDefinition></RowDefinition>

        </Grid.RowDefinitions>

        <Grid.ColumnDefinitions>

            <ColumnDefinition Width="100px"></ColumnDefinition>

            <ColumnDefinition></ColumnDefinition>

            <ColumnDefinition></ColumnDefinition>

        </Grid.ColumnDefinitions>       

    </Grid>

And this is a presentation of what could be if such alternative is used

Figure 4

The Auto definition

It means that the size is proportional to the content object size. Once the column or the row width or height is set to auto and there is no object contained with it. It disappears from the grid but it doesn't mean that it is deleted. If you add controls within, it takes exactly the control dimension. For example, if we make a rectification of the previous code

<Grid ShowGridLines="True" >

        <Grid.RowDefinitions>

            <RowDefinition></RowDefinition>

            <RowDefinition></RowDefinition>

            <RowDefinition></RowDefinition>

        </Grid.RowDefinitions>

        <Grid.ColumnDefinitions>

            <ColumnDefinition Width="Auto"></ColumnDefinition>

            <ColumnDefinition></ColumnDefinition>

            <ColumnDefinition></ColumnDefinition>

        </Grid.ColumnDefinitions>       

    </Grid>

The grid appearance will be

Figure 5

Cut  Width="Auto"  then drag and drop a button into the grid and make sure that it is contained within the row 0 , column 0 grid cellule and this is the XAML button code.

<Button Grid.Column="0" Grid.Row="0" Width="100" Name="button1">Button</Button>

Now, paste Width="Auto" exactly in its previous place and you will observe this. As you see the button is clipped rather that scrolled.

Figure 6

 

READ MORE

Visual Studio 2008 and .Net framework 3.5 provide us several new features not found in the precedent version. The WPF, the XAML and Silverlight are among the new features introduced in a WPF context. They contribute to the amelioration of the application ergonomic side by introducing something new like 2D/3D animations. For instance, Visual studio 2008 and Silverlight products must be installed before starting with animations. For me, this is my first experience within VS 2008, XAML, WPF and Silverlight.  

As you will see, a given animation can target a given control such as a rectangle, a grid or an even a button witches are called canvas. The animation by definition is this context is the given control property or properties changement from given statue to another via an interpolation that could be monitored by the developer via code xaml or via the page code behind. I mean C # code. It is similar phenomenon when comparing with the flash animations, if you have already dealt with flash projects especially the movement and the form interpolations. There are three main animations in addition to a set of witches those provided by the System.Window.Media.Animation namespace,  all could be used in order to achieve a particular goal, but in this article and the ones witches will follow this one,  we'll concentrate on the three kind of animations, namely the Double animation, the Color animation and the point animation, moreover, the .Net frameworks provides a set of base classes such DoubleAnimationBase, ColorAnimationBase and PointAnimationBase to customize your code in addition to other classes like Aniamtable and interfaces such as IAnimatable. All of them are provided to perform customized animations within your WPF application.

In this article, I will give a trick of how to deal with ColorAnimation class within VS2008 and Silverlight context using both xaml and C# 4.0, afterward, and in the two subsequent articles, we'll focus on the DoubleAnimation and PointAnimation:

The Color animation:

In this example we will define a rectangle that changes color from yellow to red if the mouse enters the given object boundaries and then returns to the first color if the mouse leaves the rectangle.

XAML code:

Create a new WPF application by open New>Project>WPFApplication then name your application my first WPF application. Copy and paste this under code to the xaml zone.

<Window x:Class="myWpfApplication.Window1"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    Title="Window1" Height="400" Width="400" Loaded="Window_Loaded">

<!—The rectangle extends the Animatable class so it can be target of an

 Animation therefore a chose it -->

    <Rectangle Width="250" Height="250" ToolTip="This is myRectangle" Name="myRectangle"Visibility="Visible" Fill="Yellow">

        <Rectangle.Triggers>

             <!—The mouse enter event is the one that triggers the animation -->

            <EventTrigger RoutedEvent="Rectangle.MouseEnter">

            <!—The Storyboard is a sort of aniamtion container-->

                <BeginStoryboard>

                    <Storyboard>

                    <!—The color, the duration, and the targeted property that will

                       Be subject of the aniamtion, all parameters are set within the animation tag  -->

                        <ColorAnimation Storyboard.TargetName="myRectangle"

                                         Storyboard.TargetProperty="(Fill).(Color)"

                                         Duration="00:00:08"

                                         From="Yellow" To="Red"                                  

                                         />

                    </Storyboard>

                </BeginStoryboard>

            </EventTrigger>

            <!—As you see, you can implement more that one animation for the same

               Object at the same time -->

          <EventTrigger RoutedEvent="Rectangle.MouseLeave">

                <BeginStoryboard>

                    <Storyboard>

                        <ColorAnimation Storyboard.TargetName="myRectangle"Storyboard.TargetProperty="(Fill).(Color)"

                                        Duration="00:00:08" From="Red" To="Yellow"

                                        />

                    </Storyboard>

                </BeginStoryboard>

            </EventTrigger>

        </Rectangle.Triggers>

    </Rectangle>

</Window>

C# code:

Also this task could be performed using the form code behind, I mean C#, to do so open a new window drag and drop a new rectangle.

Figure 1

Then right click on it and choose the properties menu.

Figure 2

Afterward, select the properties menu item and set it property name to "myRectangle" width to "250" and it height to "250".

Then implement the code as bellow, but don't forget to append System.Windows.Media.Animation namespace to the project:

//It is used to fill myRectangle object

SolidColorBrush TransformBrush;

//This animation is for changing the color

ColorAnimation oColorAnimation;

private void Window_Loaded(object sender, RoutedEventArgs e)

{

//First we set the color to yellow

TransformBrush = new SolidColorBrush(Colors.Yellow);

//Fill the rectangle using the TransformBrush

myRectangle.Fill = TransformBrush;

//Those two lines are responsibles for triggering events MouseEnter and MouseLeave

myRectangle.MouseEnter+=new MouseEventHandler(myRectangle_MouseEnter);

myRectangle.MouseLeave+=new MouseEventHandler(myRectangle_MouseLeave);

}

private void myRectangle_MouseEnter(object sender, RoutedEventArgs e)

{

//Set the animation

oColorAnimation = new ColorAnimation();

 

//The initial brush state

oColorAnimation.From = Colors.Yellow;

//The final brush state

oColorAnimation.To = Colors.Red;

//The animation duration

oColorAnimation.Duration = TimeSpan.FromSeconds(8);

//Trigger the animation

TransformBrush.BeginAnimation(SolidColorBrush.ColorProperty, oColorAnimation);

 

}

private void myRectangle_MouseLeave(object sender, RoutedEventArgs e)

{

//Set the animation

oColorAnimation = new ColorAnimation();

//The initial brush state

oColorAnimation.From = Colors.Red;

//The final brush state

oColorAnimation.To = Colors.Yellow;

//The animation duration

oColorAnimation.Duration = TimeSpan.FromSeconds(8);

//Trigger the animation

TransformBrush.BeginAnimation(SolidColorBrush.ColorProperty, oColorAnimation);

 

READ MORE
...