Confessions of a .NET Developer!

ImageViewer

Well this post is about my small ImageViewer application that I made using WPF, though I still have little more work to do to finish it completely. Anyway here is a screenshot of what I have done so far. The added advantage is that you can drag the area where all the images are shown up and down. Hope you will like it. 🙂

ImageViewer

ImageViewer

Advertisements

June 15, 2011 Posted by | WPF | 1 Comment

WPF Tutorial : Drawing Visual

As described in the MSDN, is a lightweight drawing class to render shapes, images, videos, text etc. It’s so lightweight that it needs a container to hold it, also the fact that it doesn’t provide layout or hit-testing or event-handling.

So for holding our DrawingVisual, we will use a which will provide layout, hit-testing and event-handling.

Lets get started by creating a class DrawIt which inherits FrameworkElement class. In this class we will create two rectangles using DrawingVisual class.

    class DrawIt:FrameworkElement
    {
        VisualCollection visuals;

        public DrawIt()
        {
            visuals = new VisualCollection(this);

            this.Loaded += new RoutedEventHandler(DrawIt_Loaded);
        }

        void DrawIt_Loaded(object sender, RoutedEventArgs e)
        {
            int x = 0;
            
            for (int i = 0; i <= 1; i++)
            {
                DrawingVisual visual = new DrawingVisual();
                using (DrawingContext dc = visual.RenderOpen())
                {
                    dc.DrawRectangle(Brushes.Red, new Pen(Brushes.Black, 2),
                        new Rect(new Point(0 + x, 0), new Size(40, 40)));
                }
                visuals.Add(visual);
                x += 60;
            }
        }

        protected override Visual GetVisualChild(int index)
        {
            return visuals[index];
        }

        protected override int VisualChildrenCount
        {
            get
            {
                return visuals.Count;
            }
        }
    }

Explanation :

For this class, we have defined visuals of type VisualCollection. VisualCollection will keep the number of visual objects that we have drawn so far.
In the LoadedEvent, I am running a for-loop to draw 2 rectangles. In that, a DrawingVisual object is created for every loop made. The RenderOpen() method of DrawingVisual will return an object of type DrawingContext which is used to render the content of the visual. This line is straight from MSDN: “When you use a DrawingContext object’s draw commands, you are actually storing a set of rendering instructions that will later be used by the graphics system; you are not drawing to the screen in real-time”. This will greatly improve the performance.
Then there are two overrides which will be used by our container to manage the collection of the visual objects.

Next is to display our visuals in a Window. Here is the XAML of our window.

<Window x:Class="LearnDrawing.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:LearnDrawing"
    Title="Window1" Height="300" Width="300">
    <Grid>
        <local:DrawIt Width="100" Height="100"/>
    </Grid>
</Window>

And the window will display this:

Window

Window

I would like you to read these articles too which helped me a lot:

http://jerryclin.wordpress.com/2007/11/21/lightweight-drawing-with-drawingvisuals-part-1-of-2
http://jerryclin.wordpress.com/2007/12/19/lightweight-drawing-with-drawingvisuals-part-2-of-2
http://msdn.microsoft.com/en-us/library/ms748373%28v=VS.90%29.aspx

That’s it. Hope it helped you. Happy coding!

May 19, 2011 Posted by | WPF | 1 Comment

Basic Linq to XML operations

This post shall deal with Inserting, Deleting and Modifying XML data using Linq to XML.

Here is how the XML will look like:

<?xml version="1.0" encoding="utf-8" ?>
<access>
  <user id="149">
    <name>Tarun</name>
    <age>22</age>
    <company>ABC</company>
  </user>
  <user id="13">
    <name>Gagan</name>
    <age>23</age>
    <company>Birla</company>
  </user>
  <user id="45">
    <name>Sachin</name>
    <age>24</age>
    <company>Steria</company>
  </user>
</access>

Add this XML to your project or create one using the XML Editor and set its Build Action to “Content” instead of Resource and also set Copy to Output Directory to “Copy if Newer”. With its build action set to content, I can modify the XML.

The code to Load the XML using the XDocument class under the namespace System.Xml.Linq

XDocument xDoc = XDocument.Load("XMLAccess.xml");
XElement rootElem = xDoc.Root;

And here is the way to Insert a new Record(User) into the XML :

            rootElem.Add(new XElement("user",
                new XAttribute("id", 90),
                new XElement("name", "Pulkit"),
                new XElement("age", 19),
                new XElement("company", "Infosys")));

            xDoc.Save("XMLAccess.xml");

Its quite simple using Linq, and a lot messier in case of the standard XmlDocument class.

The code to delete a User:

            XElement delElem = (from XElement elem in xDoc.Descendants("user")
                                where int.Parse(elem.Attribute("id").Value) == 90
                                select elem).Single<XElement>();

            delElem.Remove();
            xDoc.Save("XMLAccess.xml");

So the above Linq expression will return a single XElement of type user of id=90 and gets removed using a simple Remove() function.

And the code to update the XML :

            XElement updElem = (from XElement elem in xDoc.Descendants("age")
                                where int.Parse(elem.Parent.Attribute("id").Value)==45
                                select elem).Single<XElement>();

            updElem.SetValue(48);
            xDoc.Save("XMLAccess.xml");

That’s it for now. Happy coding.

May 4, 2011 Posted by | LINQ, XML | Leave a comment

FlowDocuments in WPF – Part 3

In this small post, I shall explain how to save and load the flow documents that you have created. For this, there are two classes, XamlWriter and XamlReader.
You can read more about XamlReader and XamlWriter here :
and respectively.

Create two buttons(btnSave to Save and btnOpen to Open a flowdocument) and add a FlowDocumentReader to your WPF application.

In the save button, use FileStream to create a .xaml file and save the document there.

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            using (FileStream fs = File.Open(@"C:\Save.xaml", FileMode.Create))
            {
                XamlWriter.Save(flowDocumentReader1.Document, fs);
            }
        }

Load the document from a location :

            using (FileStream fs = File.OpenRead(@"C:\Open.xaml"))
            {
                FlowDocument document = (FlowDocument)XamlReader.Load(fs);
                flowDocumentReader1.Document = document;
            }

Thats it, nothing much complicated here. Good luck!

May 1, 2011 Posted by | WPF | Leave a comment

FlowDocuments in WPF – Part 2

In this post I will be discussing Tables, BlockUIContainers and Floaters.

First lets discuss Tables. As the name suggests, you can display the data in a tabular format. Here is how it will look like :

Tables

Tables

Here is the XAML :

        <FlowDocumentReader Margin="12" Name="flowDocumentReader1">
            <FlowDocument>
                <Paragraph>Time to create a Table</Paragraph>
                <Table>
                    <Table.Columns>
                        <TableColumn Width="100"/>
                        <TableColumn Width="120"/>
                    </Table.Columns>
                    <TableRowGroup>
                        <TableRow FontSize="18" FontWeight="Bold">
                            <TableCell Background="Beige">
                                <Paragraph>Name</Paragraph>
                            </TableCell> 
                            <TableCell Background="Beige">
                                <Paragraph>Company</Paragraph>
                            </TableCell>
                        </TableRow>
                        <TableRow>
                            <TableCell>
                                <Paragraph>Gagan</Paragraph>                                
                            </TableCell>
                            <TableCell>
                                <Paragraph>BirlaSoft</Paragraph>
                            </TableCell>
                        </TableRow>
                        <TableRow>
                            <TableCell>
                                <Paragraph>Sachin</Paragraph>
                            </TableCell>
                            <TableCell>
                                <Paragraph>Steria</Paragraph>
                            </TableCell>
                        </TableRow>
                        <TableRow>
                            <TableCell>
                                <Paragraph>S.A.Kryukov</Paragraph>
                            </TableCell>
                            <TableCell>
                                <Paragraph>Milara Inc</Paragraph>
                            </TableCell>
                        </TableRow>
                        <TableRow>
                            <TableCell>
                                <Paragraph>Pulkit</Paragraph>
                            </TableCell>
                            <TableCell>
                                <Paragraph>Infosys</Paragraph>
                            </TableCell>
                        </TableRow>
                    </TableRowGroup>
                </Table>

Simple isn’t it! To define columns, use Table.Columns and define each column using TableColumn. For the row, its a bit different. Add TableRowGroup which consists of a group of TableRow’s(one for each row) which in turn contains TableCell’s(one for each column). You can do formatting to your columns by providing background colors, font size etc. Cool.

I have discussed Hyperlink in the previous post. Lets move on to BlockUIContainer.
This is one of the important features in FlowDocuments. With BlockUIContainer, you can add “non-content” elements into your FlowDocument such as Buttons, ListBox also including Layout containers like Grid and StackPanel. The only thing is that only a “single” element can be placed in it, though multiple elements can be placed in the StackPanel.
Its easy to use, here is the simple XAML :

                <BlockUIContainer>
                    <Button Height="30"
                            Width="90"
                            Content="Click Me!"
                            Name="btnBrowse"
                            Click="btnBrowse_Click"/>                            
                </BlockUIContainer>

A simple button has been inserted, you can handle the click event in the code-behind of your application.

Next up Floaters! As the name suggests, the contents of your document can “float” in your FlowDocument.
Here is what I meant :

Floaters

Floaters

And here is the XAML :

                <Paragraph>
                    WPF is a completely new presentation framework, integrating
                    the capabilities of many frameworks that have come before
                    it,
                    <Floater HorizontalAlignment="Left"
                             Width="60">
                        <BlockUIContainer>
                            <Image Source="Bear.bmp"/>    
                        </BlockUIContainer>
                    </Floater>
                    including User, GDI, GDI+, and HTML as well as being heavily
                    influenced by toolkits targeted at the Web.
                </Paragraph>

Add the Image “Bear.bmp” or any other picture as a resource in your project for easy access! Image has to be wrapped in a BlockUIContainer.

Do note the way I have placed the Image as a Floater. After the word it, the floater will be placed on the left side of the FlowDocument, and then the following sentence gets added. If you want the Image to be placed at the right, just change the HorizontalAlignment to Right.

That’s it! In the next part, I might bring adding FlowDocument programmatically. Credit goes to this book : Apress Pro WPF by Matthew MacDonald from which I learned.

Thanks for reading! Happy coding! 🙂

April 27, 2011 Posted by | WPF | 2 Comments

FlowDocuments in WPF Part 1

WPF brings out FlowDocument for readability purpose which has numerous in-built features for easing viewing of text. It actually consists of a number of blocks and resembles with HTML.
For more reading head to this link :

The MSDN says there are four types of controls:
– RichTextBox
– FlowDocumentReader
– FlowDocumentScrollViewer
– FlowDocumentPageViewer

Here I will be using FlowDocumentReader because the 3rd and 4th controls are in-built in it specified as “modes” of viewing.

Lets get started now. First of all, add the FlowDocumentReader component in your toolbox. Like below :

1) Right click on Controls header from the ToolBox and select Choose Items.

ChooseItems

ChooseItems

2) A window will open, select “WPF Component”, check the controls and click Ok.

WPF Components

WPF Components

There now we can start.
Check out this window :

SimpleWindow

SimpleWindow


That’s how a flow document will look like.

Lets try the “FlowDocumentPageViewer” mode by clicking the second control to left of the zoom control.

PageMode

PageMode

And in the Scrolling mode.

ScrollMode

ScrollMode

This is how the self-explanatory object structure of a FlowDocument looks like(taken from MSDN):

Object Model

Object Model

Here is the XAML code to create the first page of the above window :

    <Grid>
        <FlowDocumentReader Margin="12,12,12,0" Name="flowDocumentReader1">
            <FlowDocument>
                <Paragraph>
                    <Italic FontWeight="Bold">FirstParagraph</Italic>
                </Paragraph>
                <Paragraph FontFamily="Verdana"
                           FontSize="14">
                    <Run>A flow document is designed to "reflow content" depending 
                         on window size, device resolution, and other 
                         environment variables.
                    </Run>           
                </Paragraph>
                <Paragraph>
                    <Run>
                        Flow documents have a number of built in features including 
                        search, viewing modes that optimize readability, 
                        and the ability to change the size and appearance of fonts.                    </Run>
                    <Hyperlink Click="Hyperlink_Click">Now this is a hyperlink</Hyperlink>
                </Paragraph>
              </FlowDocument>
             </FlowDocumentReader>
       </Grid>

As you see, the document consists of paragraphs, where you can set the Font properties, background etc. The “Run” element is used specifically for Text only.
I have also added a Hyperlink, you can handle the click event in your code-behind, such as opening a Firefox browser etc.
You can search text which is its in-built feature together with zooming.

We can also create a List of items which look like Bullets.
Here is a window that displays it :

List

List

Here is its XAML :

                <List>
                    <ListItem>
                        <Paragraph>Tarun</Paragraph>
                    </ListItem>
                    <ListItem>
                        <Paragraph>Kumar</Paragraph>
                    </ListItem>
                    <ListItem>
                        <Paragraph>Singh</Paragraph>
                    </ListItem>
                </List>
                
                <Paragraph>A numbered List</Paragraph>
                <List MarkerStyle="Decimal">
                    <ListItem>
                        <Paragraph>WPF is awesome!</Paragraph>       
                    </ListItem>
                    <ListItem>
                        <Paragraph>Indeed it is</Paragraph>
                    </ListItem>
                </List>

Set the Marker style to get different ways of specifying the bullets and numbers.
See how neatly it has presented it.

That’s it for the first part. Next part will be about Tables and Floaters. Stay tuned! 🙂

April 25, 2011 Posted by | WPF | 1 Comment

Read Huge XML files faster

Most developers use the XmlDocument class to read XML files. LINQ has given us an excellent class XDocument which is much better than XmlDocument, inserting and deleting has become easy with XDocument. But both these classes are inefficient in handling huge XML files which are for example 500MB or 2-3 GB.

The problem is that once you load the XML using these classes, they store the whole XML in memory which eventually creates memory overheads. If you load these huge files into the memory then you might get an exception like this :
“System out of memory exception”.

So the solution for this will be to use XmlTextWriter and XmlTextReader class which is a stream-based XML reader rather than an in-memory XML reader.
These two classes read the XML node by node instead of loading the whole document. Its very much similar to using StreamWriter or StreamReader!

Lets take an example of creating an xml file from scratch.

        Dim filePath As String = "C:\Users\Tarun\Desktop\Prac.xml"
        Dim fs As FileStream = New FileStream(filePath, FileMode.Create, FileAccess.Write)
        Dim xtw As XmlTextWriter = New XmlTextWriter(fs, Text.Encoding.UTF8)

        xtw.Formatting = Formatting.Indented  ' Used so that it can be easily read while opening in Notepad
        xtw.Indentation = 4

        xtw.WriteStartDocument(True)
        xtw.WriteStartElement("Products")
        xtw.WriteComment("This is a comment")

        xtw.WriteStartElement("Product")
        xtw.WriteAttributeString("ID", "1")
        xtw.WriteAttributeString("Name", "Sony")

        xtw.WriteStartElement("Price")
        xtw.WriteString("40.33$")
        xtw.WriteEndElement()  'Closes the Price element
        xtw.WriteEndElement()  'Closes the Product element

        xtw.WriteStartElement("Product")
        xtw.WriteAttributeString("ID", "2")
        xtw.WriteAttributeString("Name", "Dell")

        xtw.WriteStartElement("Price")
        xtw.WriteString("80$")
        xtw.WriteEndElement()  'Closes the Price element
        xtw.WriteEndElement()  'Closes the Product element

        xtw.WriteEndElement()  'Closes the Products element
        'xtw.WriteEndDocument()
        xtw.Close()  'Close the XmlTextWriter stream
        fs.Close()  'Close the FileStream

The functions used are self-explanatory. But writing an XML file was not our purpose. Now lets read this XML.

        Using fs As FileStream = New FileStream(filePath, FileMode.Open, FileAccess.Read)

            Dim xtr As XmlTextReader = New XmlTextReader(fs)
            Dim writer As StringWriter = New StringWriter()
            'Read each and every node encountered
            While (xtr.Read())
                writer.Write("Type:")
                writer.Write(xtr.NodeType.ToString())

                If (xtr.Name <> "") Then
                    writer.Write("Name:")
                    writer.Write(xtr.Name)
                End If

                If (xtr.Value <> "") Then
                    writer.Write("Value:")
                    writer.Write(xtr.Value)
                End If

                If (xtr.AttributeCount > 0) Then
                    writer.Write("Attributes")
                    For i As Integer = 0 To xtr.AttributeCount - 1
                        writer.Write(" ")
                        writer.Write(xtr.GetAttribute(i))
                        writer.Write(" ")
                    Next
                End If

            End While

            Dim s As String = writer.ToString()
            Dim strm as StreamWriter = new StreamWriter("C:\HereisTheResult.txt",false);
            strm.Write(s); //Write the result to the txt file.

        End Using

April 8, 2011 Posted by | XML | Leave a comment

List all the Colors in WPF

Here I am going to make a WPF application that will list all the colors together with its HEX and its RGB value.

Here is how the Application will look like :

ColorWindow

ColorWindow

Here is the code-behind :

    public partial class ListTheColors : Window
    {
        public ListTheColors()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(ListTheColors_Loaded);
        }

        void ListTheColors_Loaded(object sender, RoutedEventArgs e)
        {           
            listColors.ItemsSource = typeof(Colors).GetProperties();
        }
    }

So here I am using Reflection to get the Properties in the Colorsclass.
The GetProperties() function will return an array of PropertyInfo which is set as ItemsSource to our ListBox.
The PropertyInfo will contain all the Public Properties of the class Colors.
We will extract the name property from it, as it will contain the name of the Color.

Lets move over to the XAML of our application :
Firstly lets specify the DataTemplate for the ListBox which is defined in the Grid.Resources

    <Grid>
        <Grid.Resources>
            <local:BrushToHexConverter x:Key="conv"/>

            <DataTemplate x:Key="BoxTemplate">
                <StackPanel Orientation="Horizontal">
                    <Border Background="{Binding Path=Name}"
                            CornerRadius="5"
                            Width="50"
                            Height="50"/>
                    <StackPanel Orientation="Vertical" Margin="5">
                        <TextBlock Text="{Binding Path=Name}" Margin="5"/>
                        <TextBlock Text="{Binding Path=Name,Converter={StaticResource conv}}" Margin="2"/>
                    </StackPanel>
                </StackPanel>
            </DataTemplate>

So the Border’s background is painted by extracting the Name property which in turn contains the name of the Color.
The first TextBlock displays the name of the Color and the second displays the A,R,G and B of the Color.
The second TextBlock’s uses a Converter to do its job which will convert the Color to RGB values.
Here is the Converter class named BrushToHexConverter which implements IValueConverter interface.

    class BrushToHexConverter:IValueConverter
    {
        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            String colorName = value.ToString();
            BrushConverter conv = new BrushConverter();
            SolidColorBrush brush = conv.ConvertFromString(colorName) as SolidColorBrush;
            Color color = brush.Color;
            StringBuilder buildString = new StringBuilder();
                buildString.AppendLine(brush.ToString()).Append("A: ").Append(color.A).Append("  R:").Append(color.R).Append("  G:").Append(color.G).Append("  B:").Append(color.B);
            return buildString;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion
    }

We use a BrushConverter class to extract the color using the ConvertFromString function which takes the name of the color(for ex. AliceBlue) and converts it to a Brush and use the Color property of the Brush to get the Color.
From that color we can extract the A,R,G and B values.

Next I have used a Style for each ListBoxItem.

            <Style x:Key="ItemStyle" TargetType="ListBoxItem">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="ListBoxItem">
                            <Border CornerRadius="2" 
                                    Margin="3"
                                    BorderBrush="Gray"
                                    BorderThickness="2">
                                <ContentPresenter Margin="2"/>
                            </Border>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>

Here is the full XAML :

    <Grid>
        <Grid.Resources>

            <local:BrushToHexConverter x:Key="conv"/>
            
            <DataTemplate x:Key="BoxTemplate">
                <StackPanel Orientation="Horizontal">
                    <Border Background="{Binding Path=Name}"
                            CornerRadius="5"
                            Width="50"
                            Height="50"/>
                    <StackPanel Orientation="Vertical" Margin="5">
                        <TextBlock Text="{Binding Path=Name}" Margin="5"/>
                        <TextBlock Text="{Binding Path=Name,Converter={StaticResource conv}}" Margin="2"/>
                    </StackPanel>
                </StackPanel>
            </DataTemplate>
            
            <Style x:Key="ItemStyle" TargetType="ListBoxItem">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="ListBoxItem">
                            <Border CornerRadius="2" 
                                    Margin="3"
                                    BorderBrush="Gray"
                                    BorderThickness="2">
                                <ContentPresenter Margin="2"/>
                            </Border>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
            
        </Grid.Resources>

        <ListBox ItemTemplate="{StaticResource BoxTemplate}"
                 ItemContainerStyle="{StaticResource ItemStyle}"
                 Name="listColors" Margin="20">
        </ListBox>
    </Grid>

Perfect!

[Edit:
I would like to add one more feature in this application. Its like adding a TextBox on top of ListBox to filter the Colors. For example, if you want to find a particular color, just type in it and it will return the results.

For this we will use the Text_Changed event of the TextBox and in it use the Filter property of the ICollectionView to filter the results.

This is the code-behind :


       private ICollectionView view;

       //Add this Loaded event of the Window
      view = CollectionViewSource.GetDefaultView(listColors.ItemsSource);

        void txtName_TextChanged(object sender, TextChangedEventArgs e)
        {
            view.Filter = delegate(object item)
            {
                PropertyInfo info = item as PropertyInfo;
                return info.Name.ToLower().StartsWith(txtName.Text.ToLower());
            };
        }

Here is how it will look like :

With Filter

With Filter

Happy coding! 🙂

March 25, 2011 Posted by | WPF | 1 Comment

Show a list of Fonts using WPF

As the headline says, I will be displaying all the available fonts in your system using WPF.

This is how it will look like :

Font Window

Font Window

So the fonts are displayed in the ListBox and the result of selecting it is shown in the TextBox.

This again will be done in XAML itself.
Here is the ListBox.

        <ListBox Margin="20,20,20,77"
                 Name="listFonts"
                 ItemsSource="{x:Static Fonts.SystemFontFamilies}"
                 FontSize="13"/>

As you can see, the way ItemsSource is set. Fonts is a Static Class and it has a Property SystemFontFamilies which is a Collection of type FontFamily.

Now what we want is that, the text written in the TextBox should have the Font Family as selected in the ListBox.

        <TextBox Height="27" Margin="20,0,20,35" Name="textBox1" Padding="3" Text="Tarun Kumar Singh" FontSize="13" VerticalAlignment="Bottom"
                 FontFamily="{Binding ElementName=listFonts, Path=SelectedItem}">            
        </TextBox>

So I have used Binding telling the FontFamily that, bind it to the selected item of the listBox.

If you want to show the Font Family in each of the ListBoxItems, then do this :

        <ListBox Margin="20,20,20,77"
                 Name="listFonts"
                 ItemsSource="{x:Static Fonts.SystemFontFamilies}"
                 FontSize="13">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding}" FontFamily="{Binding}"/>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

I have specified a DataTemplate for the ListBox. So the items displayed in ListBox will be TextBlocks and Binding its Text and FontFamily taken from the ItemsSource. This {Binding} means that it will take the source from its parent.

So it will look like this :

Font Window2

Font Window2

That’s it!
Happy Coding! 🙂

March 23, 2011 Posted by | WPF | Leave a comment

Creating a Circular Buffering Control

In this post I shall explain to create a Circular Buffering control like the one seen in websites when your video loads.
As I was learning about Animation and wrote my first post about it here :

Here is how it will look like :

Buffer

Window

No code-behind is used for this, its done in pure XAML!

Here is a Style that I am using for all the Ellipses involved :

        <Grid.Resources>            
            <Style TargetType="{x:Type Ellipse}">
                <Setter Property="Height" Value="12"/>
                <Setter Property="Width" Value="12"/>
                <Setter Property="Fill" Value="Turquoise"/>
                <Setter Property="Opacity" Value="0"/>
            </Style>
        </Grid.Resources>

<!-- And the Grid containing all the Ellipses and Animations-->

    <Grid>
        <Ellipse Margin="103,0,0,72" Name="e1" Stroke="Black" VerticalAlignment="Bottom" HorizontalAlignment="Left"/>
        <Ellipse Name="e2" Stroke="Black" VerticalAlignment="Bottom" Margin="110,0,0,86" HorizontalAlignment="Left" />
        <Ellipse Margin="126,0,0,91" Name="e3" Stroke="Black" VerticalAlignment="Bottom" HorizontalAlignment="Left" />
        <Ellipse Margin="142,0,0,87" Name="e4" Stroke="Black" VerticalAlignment="Bottom" HorizontalAlignment="Left" />
        <Ellipse HorizontalAlignment="Left" Margin="150,0,0,72" Name="e5" Stroke="Black" VerticalAlignment="Bottom"/>
        <Ellipse HorizontalAlignment="Left" Margin="110,0,0,57" Name="e8" Stroke="Black" VerticalAlignment="Bottom"/>
        <Ellipse Opacity="0" Margin="126,0,0,47" Name="e7" Stroke="Black" VerticalAlignment="Bottom" HorizontalAlignment="Left"/>
        <Ellipse HorizontalAlignment="Left" Margin="144,0,0,57" Name="e6" Stroke="Black" VerticalAlignment="Bottom"/>

        <Button Height="23" Margin="87,72,116,0" Name="button4" VerticalAlignment="Top" Content="Animate!">
            <Button.Triggers>
                <EventTrigger RoutedEvent="Button.Click">
                    <BeginStoryboard>
                        <Storyboard RepeatBehavior="Forever">
                            <DoubleAnimation Storyboard.TargetName="e1"
                                             Storyboard.TargetProperty="Opacity"
                                             From="0"
                                             To="1"
                                             AutoReverse="True"
                                             Duration="0:0:0.5"/>
                            <DoubleAnimation Storyboard.TargetName="e2"
                                             Storyboard.TargetProperty="Opacity"
                                             From="0"
                                             To="1"
                                             BeginTime="0:0:0.2"
                                             AutoReverse="True"
                                             Duration="0:0:0.5"/>
                            <DoubleAnimation Storyboard.TargetName="e3"
                                             Storyboard.TargetProperty="Opacity"
                                             From="0"
                                             To="1"
                                             BeginTime="0:0:0.4"
                                             AutoReverse="True"                                            
                                             Duration="0:0:0.5"/>
                            <DoubleAnimation Storyboard.TargetName="e4"
                                             Storyboard.TargetProperty="Opacity"
                                             From="0"
                                             To="1"
                                             AutoReverse="True"                                           
                                             BeginTime="0:0:0.6"
                                             Duration="0:0:0.5"/>
                            <DoubleAnimation Storyboard.TargetName="e5"
                                             Storyboard.TargetProperty="Opacity"
                                             From="0"
                                             To="1"
                                             AutoReverse="True"                                           
                                             BeginTime="0:0:0.8"
                                             Duration="0:0:0.5"/>
                            <DoubleAnimation Storyboard.TargetName="e6"
                                             Storyboard.TargetProperty="Opacity"
                                             From="0"
                                             To="1"
                                             AutoReverse="True"                                           
                                             BeginTime="0:0:1"
                                             Duration="0:0:0.5"/>
                            <DoubleAnimation Storyboard.TargetName="e7"
                                             Storyboard.TargetProperty="Opacity"
                                             From="0"
                                             To="1"
                                             AutoReverse="True"                                           
                                             BeginTime="0:0:1.2"
                                             Duration="0:0:0.5"/>
                            <DoubleAnimation Storyboard.TargetName="e8"
                                             Storyboard.TargetProperty="Opacity"
                                             From="0"
                                             To="1"
                                             AutoReverse="True"                                           
                                             BeginTime="0:0:1.4"
                                             Duration="0:0:0.5"/>
                        </Storyboard>
                    </BeginStoryboard>
                </EventTrigger>
            </Button.Triggers>
        </Button>
    </Grid>

So what happens here is that when the Button is Clicked a Click event is fired which will animate the 8 ellipses there.
As you can see, the BeginTime is set to every DoubleAnimation with a difference 0.2 seconds. So after first 0.2 seconds are over, the second ellipse starts, when 0.4 seconds are over, the third starts etc. AutoReverse is also given to give a fading-in fading-out effect to each ellipse.
Now you must be wondering that how come it is getting repeated over and over again. Answer is, I have set the RepeatBehaviour propety of the StoryBoard to Forever.

That’s it! It wasn’t that tough, please feel free to leave your comments, feedbacks and your valuable suggestions if you have a better idea on this.
Thanks for reading! 🙂

March 18, 2011 Posted by | WPF | Leave a comment