C++
Lesson 09: WPF Forms File Handling, Exception Handling Commandline
Windows Presentation Foundation (WPF) Binding
C#Ch9WPF.avi
up to drawing ellipse.
o File, New Project.
[pic]
You may wish to immediately run the program:
Our main window form appears:
Close the window or click
to stop.
If your design window (see next page) is not showing…..
[pic]
o Note that in our design view the Window form was produced automatically.
xmlns="
Take care that you are not dragging the grid. The grid and the Main Window are close together.
Main Window Grid
Note: If you click on their tag names in the xaml then they will be respectively selected in the design window.
We can also resize the Grid:
Take a look at the first line of the XAML.
Class specifies the name of the class which is automatically produced representing our window ( MainWindow.) This class can be found in this file MainWindow.xaml.cs. Double-click on it to open it. See below for the code.
namespace MyWPF
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
}
Controls
Make sure that your Toolbox is visible (View, Toolbox from the menu.)
Choose Common WPF Controls.
o Choose the MainWindow.xaml tab and drag a Button and a TextBox onto the grid.
With the text box selected,
from the menu choose View,
Properties. (Unfortunately
we don’t appear to be able
to right-click on the control
and choose properties but
you can just press F4.)
.
Add an Event Handler for the button as follows:
o Double-click on the button notice that this Click event handler appears.
o Type this into the button1_Click event:
.
private void button1_Click(object sender, RoutedEventArgs e)
{
textBox1.Text = "Hello";
}
o Build and Run.
Once again take note where our code was automatically produced – in the MainWindow.xml file – in our MainWindow class.
namespace myWPF
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
textBox1.Text = "Hello";
}
}
}
Reflect once again: We are drawing controls onto a form. The XAML is produced automatically, and the corresponding code is produced automatically in the corresponding Main Window .cs file!
Delete our button and text box controls. The XAML will be conveniently automatically deleted as well. (We could just as well have just deleted the XAML instead!) but note that we must delete the event handler code manually!
private void button1_Click(object sender, RoutedEventArgs e)
{
textBox1.Text = "Hello";
}
Alternatively-------------------------------------------------------------------
We could also create a new event my going to the XAML
and typing (anywhere!) in the here Click=
whereupon we are prompted for a etc.
and… quite miraculously the code is automatically generated in the corresponding .cs file:
private void Button_Click(object sender, RoutedEventArgs e)
{ }
--------------------------------------------------------------------------------------------------------------------
Time to reflect: on Binding
With WPF we have 2 files:
MainWindow.xaml
MainWindow.xaml,cs
----------------------- Whereas in Windows Forms: -------------------------------------------------------------
hese 2 files are independent! Developers could work upon each independently. Loose coupling.
Form1.cs
Form1Designer.cs
We have two .cs code files which are not as easily separated.
Containers:
Our XAML produced so far has an opening and closing Grid elements by default:
The grid is a type of container which can hold controls.
There are other containers that our main window can have:
(Actually, we are only allowed to place only one control directly onto our main window.)
We can also have a StackPanel, Canvas etc.
They all have different behaviours when the Window is resized etc.
XAML
The above could alternatively be written as
In both of these cases note that the value is written in quotes eg "200".
Equivalently to the above we could write:
200
In all cases the height of our grid will be 200.
Try them
Ref:
(Indeed this is an excellent WPF reference in general
Worth following in detail.)
The Grid properties: A grid consists of cells. A 1x1 grid is created by default.
o With the grid selected view the Properties. (Press F4)
We get 3 rows:
and the corresponding XML:
To make a row fixed width:
and corresponding xaml:
Means
Means
As well as drawing controls using the ToolBox as we have just done, we can simply cut and paste code for them! For example, we may cut and paste from this site:
Visit
Mahesh Chand csharpcorner (v good)
Accordion in WPF Toolkit
AutoCompleteTextBox in WPF
AutoComplete Folder TextBox in WPF
Area Chart in WPF
Bar Chart in WPF
Button Control in WPF
Border in WPF
Canvas in WPF
CheckBox in WPF
Calendar in WPF
Closable Tab Control in WPF
Column Chart in WPF
ComboBox in WPF
DatePicker in WPF
DockPanel in WPF
Drawing Brush in WPF
Ellipse in WPF
Expander Control in WPF
Focus Manager in WPF
GridView in WPF
Grid in WPF
Hyperlink in WPF
Icon in WPF
ImageBrush in WPF
Image Viewer in WPF
Label in WPF
Line Chart in WPF
Line in WPF eg Choose Line in WPF
ListBox in WPF
Place the Line code with this (Between the tags.) as shown:
Using Code to Add Controls
We can achieve exactly the same thing with code! First delete the above XAML that you just added. Copy this code from the previous web page (or copy it from here.) and paste it as shown below in MainWindow.xaml.cs.
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
CreateALine();
}
public void CreateALine()
{
// Create a Line
Line redLine = new Line();
redLine.X1 = 50;
redLine.Y1 = 50;
redLine.X2 = 200;
redLine.Y2 = 200;
// Create a red Brush
SolidColorBrush redBrush = new SolidColorBrush();
redBrush.Color = Colors.Red;
// Set Line's width and color
redLine.StrokeThickness = 4;
redLine.Stroke = redBrush;
// Add line to the Grid.
LayoutRoot.Children.Add(redLine);
}
}
Run the code. You should get a red line as previously.
1. Exercise. Follow the article ScrollBar in WPF
o Write some event code which will show the value of the scroll bar in a label as the scroll bar button is moved.
[pic]
Hint: First ascertain the Name of the scroll bar and then use its Value property as an indication of the scroll button's position horizontally…
…and create a Scroll event stub:
[pic]
• Change the Content property of the label ie change its "caption". (See over)
More XAML:
The Property-Value Syntax is the alternative when we have more complex ("nested") properties.
Attached Property
When the property of an element is in the child element:
The Content property
Content replaces the “Caption“ property of the old Windows Forms.
But Content is more than just a caption….
… eg it could be an image or even a StackPanel of a command button as below:
XAML Reference:
Markup Extensions
Markup extensions are dynamic placeholders for attribute values in XAML. They resolve the value of a property at runtime. Markup extensions are surrounded by curly braces (Example: Background="{StaticResource NormalBackgroundBrush}"). WPF has some built-in markup extensions, but you can write your own, by deriving from MarkupExtension. These are the built-in markup extensions:
• Eg styles
An example when using Styles
Help
WPF Resources
Window resources
Select the code that you want to comment.
Or use the control keys as suggested.
The selected code is commented
{
// Run the code
};
}
}
}
But supposed to use Despatch ie this tute: nope
my version
namespace Eds on QW.
public MainWindow()
{
InitializeComponent();
DispatcherTimer timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(1);
timer.Tick += timer_Tick;
timer.Start();
}
void timer_Tick(object sender, EventArgs e)
{
lblTime.Content = DateTime.Now.ToLongTimeString();
}
-----------------------
o WPF App(.NET Framework).
o Choose WPF Application. Call it MyWPF and click OK.
o Click Run.
o …double-click on MainWindow.xaml.
o A Grid is also produced by default in the window. This is the default container for our controls - buttons and text boxes etc.)
XAML (Extended Application Markup Language) is just a variant of XML. Like XML it is simply a text file. (Great for emailing your form to another developer!)
Like XML (and HTML) it consists of opening and closing tags
eg = 0)
{
Console.WriteLine(sr.ReadLine());
}
}
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
finally [pic]
{
}
}
}
Peek is a method which returns the next character to be read in the form of an integer. If there are no more characters then -1 is returned.
using is just a method of making sure that an object automatically goes out of scope when the using block finishes.
Streams are representations of “flat” files as objects of the StreamWriter class.
StreamWriter and StreamReader classes are used to create stream objects which are then used to transfer data to and from the opened file.
A “stream” is an object in memory which holds the data. Once we have our stream we can decide what to do with it eg convert it to XML or write it to disc which is what we are doing here..
See page 532 C# 21 days.
Close the stream as well as the file itself.
Each number eg 2 is written as a four byte integer.
ie delete it if it exists. Take care!
To run the next program from the command line:
Locate the exe file eg myproject.exe.
Open the Visual Studio command prompt. Change to the above located directory.
Type myproject c:\binFile as shown.
br.BaseStream.Length/sizeof(int)
will give us the number of integers.
DOS Commands:
cd\ will change to the root directory.
cd temp will change to the temp directory.
dir will list what’s in the current directory.
The up-arrow key will retrieve the previous DOS command.
o You could close Visual Studio if you wished.
o (You might also like to double-click on the file to run it.)
o Type cd\ and to change to c: (the root directory).
Navigate to the folder and then type exp.exe or just exp to run the executable.
Our program executes.
o Now run it from the command line but type an argument (ed) as well.
Hello
ed appears in this case.
Choose Project and the exp Properties… at the bottom of the menu drop down.
Type the command line argument here.
Hello
ed
appears as before.
using System;
using System.IO;
using System.Xml.Serialization;
// This is the class that will be serialized.
public class Table1
{
public string Name;
public decimal Balance;
}
public class Test
{
public static void Main()
{
Stream writer = new FileStream("c:\\temp\\test.xml", FileMode.Create);
XmlSerializer serializer = new XmlSerializer(typeof(Table1));
Table1 t1 = new Table1();
t1.Name = "ed" ;
t1.Balance = 10;
serializer.Serialize(writer, t1);
writer.Close();
}
}
To serialize means to send any object to a file. To deserialize means to retrieve it.
This opens the file for writing to disc.
This indicates that xml “format” that will be used to write the file to disc.
Now write the object t1 to the file.
ed
10
If Internet explorer by default displays your xml file don’t think that it is HTML. It is not - it is XML but IE is able to format XML so as well as colour coding your XML you may see + expanders etc.
using System;
using System.IO;
using System.Xml.Serialization;
// This is the class that will be serialized.
public class Table1
{
public string Name;
public decimal Balance;
}
public class Test
{
public static void Main()
{
Stream reader = new FileStream("c:\\temp\\test.xml", FileMode.Open);
XmlSerializer serializer = new XmlSerializer(typeof(Table1));
Table1 t1 = new Table1();
t1 = (Table1) serializer.Deserialize(reader);
Console.WriteLine(t1.Name + "\t " + t1.Balance);
}
}
This program simply converts a string to upper case.
o Then change this to string s = null;
Firstly: The code that could possibly throw an exception is put in the try block.
The code to handle the thrown exception is placed in the catch block just after the try block. This is called catching the exception
If an exception is raised during the execution of the code inside the try block, the remaining code in the try block is neglected (If there is any.) Try it.
(The code that must always be executed after the try or try.. .catch block is placed in the finally block, placed just after the try or try...catch blocks. This code is guaranteed to always be executed whether the exception occurs or not. See bottom of this page.)
Catch will currently catch all errors from the try.
o 2. Restore string s = null; and replace catch with catch(NullReferenceException).
This will now catch only this particular error. (ie the null string.) BUT if any other type of error occurs eg a CompareTo error it won’t be “trapped” eg if we tried to compare a string to an integer (s = "ed";)
int j = pareTo('a'); would cause a run-time exception. Try it,
o 3. Add: Console.WriteLine("No Error");
in the try block. This will be output only if there is no error. Try it in both cases.
The last line is also always executed - error or not.
•
Uncheck:
Console.WriteLine("Error");
Console.WriteLine(e);
Console.WriteLine(e.StackTrace);
Console.WriteLine(e.Message);
We could equally write:
catch (System.Exception e)
Also a list of methods which can be thrown is shown by hovering the mouse over a system method:
[pic]
arr[3]; does not exist.
o Change this to:
catch (IndexOutOfRangeException e)
Now only this specific error will be trapped.
(Any other error will cause a runtime exception.)
arr[2]) is zero.
If you don’t need to access its properties you can just have:
catch (DivideByZeroException)
Generally the more specific error catches are placed first.
This will catch any OTHER exception which may occur
This “general” catch block must come AFTER the specific catch blocks.
(Label here is in the scope of MainWindow.)
................
................
In order to avoid copyright disputes, this page is only a partial summary.
To fulfill the demand for quickly locating and searching documents.
It is intelligent file search solution for home and business.
Related searches
- c reactive protein level 30
- c reactive protein level chart
- does emergen c work
- is emergen c good for you
- c words to describe someone
- c reactive protein high
- c reactive protein high treatment
- c reactive protein elevated autoimmune
- does emergen c really work
- what is c reactive protein levels mean
- high c reactive protein autoimmune
- elevated c reactive protein foods