Archive for 2013

WPF Charts

For my 3rd year SEP project my supervisor want me to add mathematical graphs for the Question Generating System. So I was looking for WPF libraries. I found several libraries for graphing but there was no proper documentation. Finally I found a book about WPF graphing called “practical WPF graphs and graphics” by Jack Xu. So I could easily draw graphs inside application. So I am going to put an article about how to draw a graph inside a WPF application.



It is easy to create a 2D X-Y line chart in WPF. Let’s use an example to illustrate the procedure. Start with
a new WPF Windows project and name it LineCharts. Add a new WPF Window to the project and name it
SimpleLineChart. I’ll create the user interface and layout using XAML and perform the computations
and generate the data in code. The XAML file for this example is very simple:



<Window x:Class="LineCharts.SimpleLineChart"

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

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

Title="Simple Line Chart" Height="300" Width="300">

<Grid Margin="0" x:Name ="chartGrid" ClipToBounds="True"

Background="Transparent" SizeChanged="chartGrid_SizeChanged">

<Border HorizontalAlignment="Center" VerticalAlignment="Center"

BorderBrush="Gray" BorderThickness="1"

Background="White" Margin="0">

<Canvas Margin="0" x:Name ="chartCanvas" ClipToBounds="True"

Background="Transparent"/>

</Border>

</Grid>

</Window>

Here I implement a resizable Canvas element, chartCanvas, on which we want to create the
simple line chart. Here is the corresponding code-behind file, which creates the line chart, for this
example:

using System;

using System.Collections.Generic;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Shapes;

namespace LineCharts

{

public partial class SimpleLineChart : System.Windows.Window

{

private double xmin = 0;

private double xmax = 6.5;

private double ymin = -1.1;

private double ymax = 1.1;

private Polyline pl;

public SimpleLineChart()

{

InitializeComponent();

}

private void AddChart()

{

// Draw sine curve:

pl = new Polyline();

pl.Stroke = Brushes.Black;

for (int i = 0; i < 70; i++)

{

double x = i/5.0;

double y = Math.Sin(x);

pl.Points.Add(NormalizePoint(new Point(x, y)));

}

chartCanvas.Children.Add(pl);

// Draw cosine curve:

pl = new Polyline();

pl.Stroke = Brushes.Black;

pl.StrokeDashArray = new DoubleCollection(new double[] { 4, 3 });

for (int i = 0; i < 70; i++)

{

double x = i / 5.0;

double y = Math.Cos(x);

pl.Points.Add(NormalizePoint(new Point(x, y)));

}

chartCanvas.Children.Add(pl);

}

private Point NormalizePoint(Point pt)

{

Point result = new Point();

result.X = (pt.X - xmin) * chartCanvas.Width / (xmax - xmin);

result.Y = chartCanvas.Height –

(pt.Y - ymin) * chartCanvas.Height / (ymax - ymin);

return result;

}

private void chartGrid_SizeChanged(object sender, SizeChangedEventArgs e)

{

chartCanvas.Width = chartGrid.ActualWidth;

chartCanvas.Height = chartGrid.ActualHeight;

chartCanvas.Children.Clear();

AddChart();

}

}

}

Thursday, September 26, 2013
Posted by ජේ
Tag : ,

WPF Metro



What is metro?
In Windows Phone 7, Microsoft introduced its Metro style user interface. The Metro style UI is the touch-and-tile interface that Microsoft designed to create an interface focused on content, information, and movement. It is designed to embrace 5 principles: clean, light, fast, open aesthetics; dynamic, moving transitions and interactions; embrace the beauty of typography; content-focused interface; and authentically digital design.
The user interface for Windows 8 will be the Metro style UI. The Metro style works particularly well with new tablet and touch-screen devices. Windows 8 features such as user log in with tap and trace gestures, and accessing the new charms menu with a swipe are just a couple of the ways in which Microsoft uses the Metro UI to work well with new hardware as well as hardware users already own.
In the present, lot of desktop and web designers use metro concepts to develop their products, because it is very attractive and it is the trend. For our 3rd year project system totally developed base on Metro concepts.
In this post I am going to discuss how to add Metro style for our desktop applications.

Our project, we use Mahapps.metro which is easily download via Nugets. Simply go to Nuget console in visual studio and type PM> Install-Package MahApps.Metro
Official documentation :- http://mahapps.com/MahApps.Metro/


The main disadvantage is style colors are not working properly. So we can’t use style colors.
The other ways to implement Metro in WPF.
1) One way is use Elysium.
Elysium can download by :- http://elysium.codeplex.com/

This is good library and have lot of metro controls but major problem is, haven’t a documentation to learn about controls. we can use only black and white as the application background color is also a problem.



2) The other best option is <m:ui/>
Download by:- http://mui.codeplex.com/

This is also a best option and this theme is good for MVVM WPF projects. Because it has an option to change the theme in run time Big problem is, there is no proper documentation. And some important controls that need to create metro GUIS are missing.

Posted by ජේ
Tag : ,

WPF Animations

Windows Presentation Foundation (WPF) is a Computer Software graphical subsystem for rendering user interfaces in Windows-based applications by Microsoft. WPF attempts to provide a consistent programming model for building applications and separates the user interface from business logic. WPF use XAML to define and link various UI elements. WPF applications can also be deployed as standalone desktop programs, or hosted as an embedded object in a website. WPF aims to unify a number of common user interface elements, such as 2D/3D rendering, vector graphics, run time animation, and pre-rendered media.



How to do animations in WPF?

If you understand a few important concepts about the timing system, WPF animations can be easier to use. Most important is that, in WPF, you animate objects by applying animation to their individual properties. For example, to make a framework element grow, you animate its Width and Height properties. To make an object fade from view, you animate its Opacity property.

In this blog post I am going to discuss two ways of doing WPF animations. So I am going to show how to do a fade in fade out animation to a Text Box by using its Opacity property.


1)
First we need to write an animation method to a given time period. My first approach I am going to implement it inside the window resources.

<Window.Resources>
        <Style TargetType="FrameworkElement"  x:Key="animatedTxt">
           
            <Setter   Property="Visibility" Value="Hidden"/>
            <Style.Triggers>
                <Trigger Property="Visibility" Value="Visible">
                    <Trigger.EnterActions>
                        <BeginStoryboard>
                            <Storyboard>
                                <DoubleAnimation Storyboard.TargetProperty="Opacity"
                             From="0.0" To="1.0" Duration="0:0:0.6"/>
                            </Storyboard>
                        </BeginStoryboard>
                    </Trigger.EnterActions>
                </Trigger>
            </Style.Triggers>
        </Style>
           
    </Window.Resources>

When the Text Box visibility property changes Hidden to Visible animation get automatically fire. To apply an animation to an object, I create a Storyboard and use the Target Property attached properties to specify the object and property to animate. Because the Opacity property is of type Double, you need an animation that produces double values. A DoubleAnimation is use for that purpose. A DoubleAnimation creates a transition between two double values. To specify its starting value, set From property. To specify its ending value, set To property.

Then I am going to bind this animation method with the Text Box.

<TextBox Style="{StaticResource animatedTxt}" x:Name="txtAnimation"  Height="23" Margin="10,27,0,0" TextWrapping="Wrap"  VerticalAlignment="Top" Width="142" />

Then I change the visibility property of the Text Box to Visible by using a Button in run time then it appears the fade animation that I have done to the Text Box.
C# code for Visibility change

private void mouseclick(object sender, RoutedEventArgs e)
{
txtAnimation.Visibility = Visibility.Visible;
}

2)
In my second approach I am going to implement an animation which is fire for a Button click. So I add a Button and a Text Box. Inside the Button XAML tag I am going to implement the animation method.

<Button x:Name="btnAnimation" Content="" Margin="565,3,212,8" Width="40" Height="40" Click="btnCrtCht_Click" >
       <Button.Triggers>
         <EventTrigger RoutedEvent="Button.Click">
         <BeginStoryboard>
              <Storyboard>
               <DoubleAnimationUsingKeyFrames BeginTime="00:00:00"
                        Storyboard.TargetName="txtAnimation"
                        Storyboard.TargetProperty="(Canvas.Opacity)">
                             <SplineDoubleKeyFrame KeyTime="00:00:00.00" Value="0.0"/>
                             <SplineDoubleKeyFrame KeyTime="00:00:1.50" Value="1"/>
                </DoubleAnimationUsingKeyFrames>
              </Storyboard>
        </BeginStoryboard>
</EventTrigger>
</Button.Triggers>
</Button>

XAML code for the Text Box

<TextBox x:Name="txtAnimation"  Height="23" Margin="10,27,0,0" TextWrapping="Wrap"  VerticalAlignment="Top" Width="142" />

Run and see the animation.






Posted by ජේ
Tag : ,

How to Export an xml file from WPF application

In my 3rd year project I had to export an xml file which contains data about questions for moodle. To do this task I use xml writer. So I am going to discuss how to read data from a DataGrid and export data as an xml file.

First add this headers

using System.Xml.Serialization;
using System.IO;
using System.Xml;
using System.Data;

This is the code for xml writer

System.Windows.Forms.SaveFileDialog sf = new System.Windows.Forms.SaveFileDialog();
            sf.AddExtension = true;
            sf.DefaultExt = "xml";
            sf.ShowDialog();

            if (sf.FileName != "")
            {
                using (XmlWriter writer = XmlWriter.Create(@sf.FileName))
                {
                    writer.WriteStartDocument();
                    writer.WriteStartElement("quiz");
                    //add all true false questions
                    for (int r = 0; r < gridTrFaQues.Items.Count - 1; r++)
                    {

                        DataRowView row = (DataRowView)gridTrFaQues.Items[r];

                        writer.WriteStartElement("question");
                        writer.WriteAttributeString("type""multichoice");
                        writer.WriteStartElement("name");
                        writer.WriteElementString("text""True False Questions " + (i)); 
                        writer.WriteEndElement();
                        writer.WriteStartElement("questiontext");
                        writer.WriteAttributeString("format""html");
                        writer.WriteElementString("text", row.Row.ItemArray[0].ToString());
                        writer.WriteEndElement();
                        writer.WriteStartElement("generalfeedback");
                        writer.WriteElementString("text""general feedback");
                        writer.WriteEndElement();
                        writer.WriteElementString("defaultgrade""1");
                        writer.WriteElementString("penalty""0");
                        writer.WriteElementString("hidden""0");
                        writer.WriteElementString("single""true");
                        writer.WriteElementString("shuffleanswers""true");
                        writer.WriteStartElement("correctfeedback");
                        writer.WriteElementString("text""correct feedback");
                        writer.WriteEndElement();
                        writer.WriteStartElement("partiallycorrectfeedback");
                        writer.WriteElementString("text""partiallycorrect feedback");
                        writer.WriteEndElement();
                        writer.WriteStartElement("incorrectfeedback");
                        writer.WriteElementString("text""incorrect feedback");
                        writer.WriteEndElement();
                        writer.WriteStartElement("answer");
                        writer.WriteAttributeString("fraction""100");
                        writer.WriteElementString("text", row.Row.ItemArray[1].ToString());
                        writer.WriteStartElement("feedback");
                        writer.WriteEndElement();
                        writer.WriteEndElement();
                        writer.WriteStartElement("answer");
                        writer.WriteAttributeString("fraction""0");
                        writer.WriteElementString("text", row.Row.ItemArray[2].ToString());
                        writer.WriteStartElement("feedback");
                        writer.WriteEndElement();
                        writer.WriteEndElement();
                        writer.WriteStartElement("answer");
                        writer.WriteAttributeString("fraction""0");
                        writer.WriteElementString("text", row.Row.ItemArray[3].ToString());
                        writer.WriteStartElement("feedback");
                        writer.WriteEndElement();
                        writer.WriteEndElement();
                        writer.WriteStartElement("answer");
                        writer.WriteAttributeString("fraction""0");
                        writer.WriteElementString("text", row.Row.ItemArray[4].ToString());
                        writer.WriteStartElement("feedback");
                        writer.WriteEndElement();
                        writer.WriteEndElement();
                        writer.WriteEndElement();
                       
                    }
writer.WriteEndElement();
                    writer.WriteEndDocument();
                }



In this code I use a Save File Dialog to get the save point of the xml file. gridTrFaQues is the DataGrid name that I use to get data.

sample xml file for above code


<quiz>

<question type="multichoice">

<name>

<text>Common Questions 1</text>

</name>

<questiontext format="html">

<text>test ques</text>

</questiontext>

<generalfeedback>

<text>general feedback</text>

</generalfeedback>

<defaultgrade>1</defaultgrade>

<penalty>0</penalty>

<hidden>0</hidden>

<single>true</single>

<shuffleanswers>true</shuffleanswers>

<correctfeedback>

<text>correct feedback</text>

</correctfeedback>

<partiallycorrectfeedback>

<text>partiallycorrect feedback</text>

</partiallycorrectfeedback>

<incorrectfeedback>

<text>incorrect feedback</text>

</incorrectfeedback>

<answer fraction="100">

<text>1 answer</text>

<feedback/>

</answer>

<answer fraction="0">

<text>2 answer</text>

<feedback/>

</answer>

<answer fraction="0">

<text>3 answer</text>

<feedback/>

</answer>

<answer fraction="0">

<text>4 answer</text>

<feedback/>

</answer>

</question>

</quiz>
Posted by ජේ
Tag : ,

10 WPF tips

Today I am going to discuss about very useful tips in WPF application developing.
1) How to validate a Text Box using regular expressions.

This is very easy no more need to use if else blocks and lengthy codes to validate the Text Boxes only need regular expressions.

· Add this to top of the class
using System.Text.RegularExpressions;
· Method that implement the validation for the textbox
If you use this method to a Text box it can be typed only numbers
private void NumberValidationTextBox(object sender, TextCompositionEventArgs e)
        {
            Regex regex = new Regex("[^0-9.-]+");
            e.Handled = regex.IsMatch(e.Text);
        }

· Then bind the method to a relevant Text box
<TextBox Name="txtVara" PreviewTextInput="NumberValidationTextBox"/>

2) How to navigate to a video or web site using button

Sometimes we want to navigate websites and videos outside the WPF application let’s see how to do it.

string path = new System.IO.FileInfo("WebHelp/QGSHelp.htm").FullName;
System.Diagnostics.Process.Start(path);
What I do is simply pass the file path. :)

3) How to use web control tool in WPF

Many interfaces are implemented with websites. In a WPF program, we provide access to websites (and other data sources) with the WebBrowser control. WebBrowser uses the Internet Explorer rendering engine.

<WebBrowser x:Name="Browser" HorizontalAlignment="Left" Height="228" Margin="10,222,0,0" VerticalAlignment="Top" Width="450"/>

How to navigate a web to a web Browser control
Browser.Navigate("http://en.wikipedia.org/");

How to navigate a web page stored inside hard disk
Browser.Source = new Uri(new System.IO.FileInfo("TexWeb/Tex.html").FullName);

4) WPF toolkit

Extended WPF Toolkit™ is the number one collection of WPF controls, components and utilities for creating next generation Windows applications. Use it to build professional looking, modern, and easy to use line of business applications. This is very useful tool kit set for developing WPF applications

Download from:- https://wpftoolkit.codeplex.com/

5) How to add objects to the Data Grid

First make a class for objects that you want to add to the Data Grid

public class test
       {
       
        public string question { getset; }
        public string answer { getset; }
        public string wanswer1 { getset; }
        public string wanswer2 { getset; }
        public string wanswer3 { getset; }
}

Add the Data Grid

DataGrid x:Name="dataGrid" >
       <DataGrid.Columns>
       <DataGridTextColumn Binding="{Binding question}"  Header="Question"/>
        <DataGridTextColumn Binding="{Binding answer}"  Header="Answer"/>
       <DataGridTextColumn Binding="{Binding wanswer1}"  Header="Wrong Answer1"/>
       <DataGridTextColumn Binding="{Binding wanswer2}"  Header="Wrong Answer2"/>
        <DataGridTextColumn Binding="{Binding wanswer3}"  Header="Wrong Answer3"/>
                </DataGrid.Columns>
            </DataGrid>

Add object to the data grid
dataGrid.Items.Add(new test { question ="ques", answer ="ans", wanswer1 = "w1", wanswer2 = "w2", wanswer3 = "w3"});

6) Add template Column to the Data Grid

                <DataGrid >
                <DataGrid.Columns>
                    <DataGridTextColumn Header="header"/>
                 <DataGridTemplateColumn Header="Image" >
                  <DataGridTemplateColumn.CellTemplate>
                   <DataTemplate>
                  <Image Height="114" Width="163" Source="{Binding imgPath}" ></Image>
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>
                </DataGrid.Columns>
            </DataGrid>

7) How to convert image to base 64 string and How to convert Base64 string to Image

Image to base 64
private string getBase64(string path)
        {
            FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
            byte[] data = new byte[fs.Length];
            fs.Read(data, 0, (int)fs.Length);
            fs.Close();
            return System.Convert.ToBase64String(data);
        }
Base64 to Image
private BitmapImage GetImage(string base64String)
        {
            byte[] binaryData = Convert.FromBase64String(base64String);
            BitmapImage bi = new BitmapImage();
            bi.BeginInit();
            bi.StreamSource = new MemoryStream(binaryData);
            bi.EndInit();
            return bi;
                    }

8) View Box Control

The ViewBox is a very useful control in WPF. If does nothing more than scale to fit the content to the available size. It does not resize the content, but it transforms it. This means that also all text sizes and line widths were scaled. It’s about the same behavior as if you set the Stretch property on an Image or Path to Uniform. This is the solution for resolution problems.

Although it can be used to fit any type of control, it's often used for 2D graphics, or to fit a scalable part of a user interface into a screen area.
<Button Content="Test" />
  <Viewbox Stretch="Uniform">
     <Button Content="Test" />
</Viewbox>




9) MediaElement

If you want play a video inside the wpf application better option is use a MediaElement.
It’s quite easy to add a video player into a WPF .xaml window.
Drag and drop the 'MediaElement' to the .xaml window.

On the form loaded event, write the following code
mediaElement1.Source = new Uri(@"F:\Media\Memory Card\Media\Video\2.MP4");

Change the 'uri' path to the location where you stored your favorite videos.

10) How to use specific Windows theme in a WPF application

WPF includes all common Windows themes. By default WPF loads the current Windows theme as your default style-set. But you can override these styles by loading a specific theme. To do this you first have to add a reference to the style assembly you like to use and second you need to merge the theme resource dictionary into your app resources. This overrides the default style-set that has been loaded by WPF.

The following example shows how to load the Windows Vista Aero theme. Open App.xaml and add this.
<App.Resources>
    <ResourceDictionary Source="/PresentationFramework.Aero, Version=3.0.0.0,
     Culture=neutral, PublicKeyToken=31bf3856ad364e35,
rocessorArchitecture=MSIL;component/themes/aero.normalcolor.xaml" />
</App.Resources>



Posted by ජේ
Tag : ,

Popular Post

Total Pageviews

Powered by Blogger.

- Copyright © sharpish j -Metrominimalist- Powered by Blogger - Designed by Johanes Djogan -