Introduction

 Top Next

PHH - 20th. January 2011


Terminology and Abbreviations

 Top Previous Next

Standard :

RIA - Rich Interactive Applications

WPF - Windows Presentation Foundation

XAML - Extensible Application Markup Language

Mine :

SL - Silverlight

PHH - 20th. January 2011


What is Silverlight

Let us keep this simple - we need a quick, solid, but correct definition, or statement, with

which to work.

Silverlight (SL) is a reduced set (or section) of the technology which we know as WPF.

The XAML design surface and mark-up script is basically the same, or at least VERY similar,

and many elements or controls are common to both.

It does need to be pointed out however, that because SL is running in a Browser, and capable of running

on a hardware platform which is NOT running Windows, there are some important differences with which we

will need to become familiar.

*** MANY skills will transfer over from WPF form design into the world of Silverlight - and vice versa.

About the hardest thing we need do as developers is find out , then learn, what these few differences are.

It may also be a good idea that we find a way which works for both SL and WPF and stick with it, rather

than use a bunch of techniques which are only available in WPF, then have to apply an alternative in SL development.

I for one will be looking out for a raft (or host) of things which work the same on both the SL and WPF platforms.

If you can use WPF then you can use Silverlight :

There is such an overlap of the skills, and abilities, of development and form creation with WPF, and those required

for Silverlight development, that MANY of our concerns can be forgotten. We just to to make the time to sit down

have some fun ;0))

We as developers, just need to be aware of the fact that there are differences, and posses some good and clear

examples of both approaches of the underlying technology - then we are well on our way to success.

Time and practise is the key to success !!

See you in the next section ............

PHH - 20th. January 2011


Relating Silverlight to WPF

Let us start with a look at what the SDK documentation has to say on the matter :-

================================================================================================================================

================================================================================================================================

PHH - 20th. January 2011


Features with Reduced Support

================================================================================================================================

PHH - 31st. January 2011.


Different Approach

================================================================================================================================

PHH - 31st. January 2011.


SL only Features

================================================================================================================================

PHH - 31st. January 2011.


Others

================================================================================================================================

PHH - 31st. January 2011.


Observed Differences - my own notes

Examples of Differences :

in-line coding of event handlers.

? colours available to brushes etc. - NOT

tooltips

click event - mode

menu bars

toolbars

PHH - 31st. January 2011.


Overview of these eNotes

PHH - 20th. January 2011


Controls Common to SL and WPF

PHH - 20th. January 2011


Controls ONLY in Siverlight

PHH - 20th. January 2011


Controls ONLY in WPF

The following are "Not Available" for Silverlight :-

AccessText

AdornedElementPlaceholder

AdornerDecorator

BulletChrome

BulletDecorator

ButtonChrome

ClassicBorderDecorator

ContextMenu

Decorator

DocumentPageView

DocumentReference

DocumentViewer

FixedPage

FlowDocumentPageViewer

FlowDocumentReader

FlowDocumentScrollViewer

GridViewColumnHeader

GridViewHeaderRowPresenter

GridViewRowPresenter

GroupBox

GroupItem

InkCanvas

ListBoxChrome

ListView

ListViewItem

Menu

MenuItem

NavigationWindow - Not available, but see Frame

PageContent

PageFunction

ResizeGrip

Ribbon

RibbonWindow

ScrollChrome

Separator

StatusBar

StatusBarItem

SystemDropShadowChrome

TickBar

ToolBar

ToolBarOverflowPanel

ToolBarPanel

ToolBarTray

Track

UniformGrid

Viewport3D

WindowsFormsHost

PHH - 20th. January 2011


Controls - SL only at Runtime

Border

Button

Canvas

CheckBox

ComboBox

ComboBoxItem

ContentControl

ContentPresenter

Ellipse

FrameworkElement

Glyphs

Grid

Hyperlink

HyperlinkButton

Image

InkPresenter

ItemsControl

ItemsPresenter

Line

ListBox

ListBoxItem

MediaElement

MultiScaleImage

PasswordBox

Path

Polygon

Polyline

Popup

ProgressBar

RadioButton

Rectangle

RepeatButton

RichTextBox

ScrollBar

ScrollContentPresenter

ScrollViewer

Slider

StackPanel

TextBlock

TextBox

Thumb

ToggleButton

ToolTip

UserControl

ViewBox

VirtualizingStackPanel

WebBrowserBrush

WebBrowser

Window - Runtime (out-of-browser only)

PHH - 20th. January 2011


Navigation from Form to Form

If we simply look into the SDK documentation at the 'WPF Compatibility' section { I use the CHM version which is

freely downloadable from MS } we see the following details :-

[ ** CARE ** later documentation shows 'ContextMenu' in a Toolkit namespace !! ]

{ .. we need to keep updating our related information from the Toolkit download sites .. }

......................................................................

......................................................................

......................................................................

......................................................................

=============================================================================================

To my simple mind this immediately suggests that the standard desktop approach to navigating between forms and

dialogue screens is different in SL.

Maybe we may get a hint of what to use in place of selecting menu items and clicking toolbar icons, by seeing what is

available ONLY to Silverlight - see below :-

=================================================================================================

There are only eight entries which are for SL alone. Three to be found in the 'Runtime', four in the SDK (SL) itself,

and one in the 'SL toolkit'.

PHH - 20th. January 2011.


Silverlight Toolkit(s)

The Silverlight Toolkit if a way the Microsoft guys can keep adding to the SL set of controls without need

to cause too much disruption to us developers, or to keep us waiting for a major update.

In the images below I have recorded the information from my live download and install of the most recent

Toolkit (as of January 20th. 2011).

======================================================================================================================================================================

======================================================================================================================================================================

Now that we have all the Toolkit stuff, what have we got available to us that we have not got in the

regular Toolbox ?

This seems a difficult one to get right, or 'spot on', as things change with time, and old entries in the

Toolkit may become standard entries in later major updates. However, we can at least list out what is

currently in the list associated with this download.

Here is the best list I can find :-

Accordion

AutoCompleteBox

Calendar

DatePicker

DockPanel

-------------------------------------

DomainUpDown

Expander

GlobalCalendar

GridSplitter

HeaderedContentControl

--------------------------------------

HeaderedItemsControl

Label

LayoutTransformer

NumericUpDown

Rating

--------------------------------------

TabControl

TimePicker / RangeTimePickerPopup / ListTimePickerPopup

TimeUpDown

TransitioningContentControl

TreeView

---------------------------------------

Viewbox

WrapPanel

About 24 in total according to my SDK docs. Notice that when the tool is used from the Toolbox we see

a prefix added of 'toolkit:' and the image below demonstrates this nicely :-

=========================================================================================

We also see that the default References included by the C# template I used gives the following

in the SE pane :-

[ incorrect - they are added on the fly as tools are dragged from the Toolbox !! - more investigation required ]

==========================================================

In the image shown above we see two assemblies for 'Toolkit'.

Basically, from the Toolbox list before it is ordered alphabetically, it is hard to tell 'exactly' which items are

from the Toolkit namespaces - BUT - a few can be seen in the following image, and all items appear in the list

after the standard SL ones :-

==========================================

Studying the above list we can even see that my recent download gave me a 'ContextMenu' element which

was not in the Silverlight 4 CHM file I downloaded from MS - so things appear to be changing all the time as far

as getting new tools is concerned.

See below for an example of the 'ContextMenu' :-

==============================================================================================

Once again, notice the 'toolkit' prefix in the XAML script generated by dragging from the Toolbox.

Whereas both 'Viewbox' and 'TreeView' have been added to the standard sets of controls,

===================================================================================================

Below is what is added to the References section when we drag a 'BarSeries' control :-

===============================================================================================================

Looking down the rest of the tools in the box we see some others (quite a few) which are graphically

oriented - like those related to pies, lines and bubbles etc. etc..

Notice ho the 'BubbleSeries' has a prefix :-

============================================================================================================================================

Finally, for this section, we see a bunch of 'stacked' elements too - see below :-

=======================================================================================================================================

And after all that messing with selecting 'extras' from the toolkits we have a SE pane which looks

like this below :-

To summarize - simply keep on the lookout for new controls being made available to us at frequent intervals

I would suggest after this chunk of research ;-)

See you in the next section ...................

PHH - 20th. January 2011.


Chapter 1 - Making a Start

Okay you guys, let us roll up our sleeves and get learning - Silverlight 4 here we come !!!

Open up your VS10 shell and close all previous solutions and projects.

Go to the main menu and select File ... New ...

You should get a dialog box/screen like this below :-

[ ** note ** we have to use C# at the moment because the SL template for Vulcan needs to be created .. ]

[ .... this is not much of an issue as we are going to be doing a lot with XAML and the mark-up design surface .. ]

Now change the 'Name' to something suitable - see below for my choice :-

Once you have clicked the OK button you get a dialog box to help you choose a web site or just an alternative 'Local' option.

Here is what it looks like :-

The consequence of selecting the local option is that we get two files created when we build and run.

These files will then need to be manually uploaded to our web site from which they can be run.

However, we can build and run in test mode, where the SL/WPF system uses the local entries to run through

our local Browser.

Below is shown the results of our efforts, both the XAML script editor entry, and the graphical surface too :-

=========================================================================================================

And before we get into discussions about details, here is what the Solution Explorer (SE) pane looks like :-

==========================================

So the quick summary is that we now have a C# solution / project and the code behind is therefore in C#, whereas the

'Script in Front' is XAML. Any event handling code will need to be added to the code behind section and C# used for this.

Silverlight projects (as with WPF ones) have 'Code Behind' and also 'Script in Front'.

The trick is to know what to place in the Script in Front, and what to keep in the Code Behind. This is one thing that

we hope will become clearer as we make our explorations into possible ways to design and create Silverlight Apps.

Some Early Observations :

The VS10 shell called the project a 'Silverlight Application' - so 'app' it is to you and me.

Looking at the default XAML script, we have a 'UserControl' and not a 'Window' as in WPF. So the opening and

closing tags are those for <UserControl>.

If we build and run at this stage we don't get a lot to see ;-) In fact we see and empty Browser - see below :-

The absence of any apparent output is simply because we have not done sufficient yet in our XAML script to

allow anything to show - maybe a colour or two would help, even though we have no other elements yet.

One thing we do see is the files we have created at build time.

Study the image below to see what we have created :-

======================================================================================================================================================

It is the two files named 'ClickStart2.xap' and 'ClickStart2TestPage.html' which we will need to copy to

a web site folder, later in these notes - next chapter I believe.

If we do a shell execute (double click with the mouse) on the '.html' file we get the same Browser launch

and 'blank' result as when we built and ran.

So in the web area we just need to make an active link to this '.html' file and have the '.xap' file available in

the same directory.

Making Something Visible :

First of all, it is VERY simple to change the background on the User Control from white to a nice colour !

It would seem sensible to make the main element coloured, and so I have made the UserControl a 'brave'

tomato color - however, this does not appear to show.

========================================================================

I have even made sure the grid element occupies less area than the UC - I then coloured the Grid a nice turquoise

and we start to see things - check out below :-

========================================================================================================

Eagle eyed guys will notice that I must have previously selected the turquoise other wise it would not be already

showing in the graphical design surface.

Sizing the Root :

It would appear that the main element - in this case a 'UserControl' - is called the root.

If this element is made to have focus then we get a symbol (with tooltip) which shows the state (or mode)

when the element is displayed in the Browser.

Below the diagonal arrow symbol is displayed to show it will resize correctly when the Browser is resized.

================================================================================================

The alternative is to leave it where it is and the symbol for this 'state' is shown below :-

[ .. click the symbol to change the 'state' or 'mode' .. ]

=================================================================================================

In the following image I have attempted to show the two alternatives on the same overlapped image.

The best way is for you to try it yourself ;-)

Study this :-

Let us now move into the following subsection where we can start to add some functionality to our

first Silverlight app - even if it is just a few passive controls, some within another.

Remember form WPF, we used to say 'things within things'.

See you in the next section .....

PHH - 20th. January 2011


First simple Local app

For this project let us uncheck the 'Show All' option for the Toolbox pane, and only open the

folder (tab) for the 'Common Silverlight Controls' - see below :-

================================================================================

This should be enough to work with for a couple projects I should think ;-)

Let us maximise the Grid to the full graphical size of the UC, so we have some more room to play with.

Adding Columns and Rows to the Grid :

With the Grid element in focus - see below :-

===================================================================================================================

Place the cursor in the left hand 'active side of the Grid boundary, and when positioned correctly click the left mouse

button to create the new row - see below for 'before' creation :-

================================================================

And now let us see what we did when we clicked :-

============================================================================================================

Yes, we have two rows, with heights as shown in XAML script and on the graphical surface - proportions of 94 to 205.

I have now gone back to the designer and created one more row, and then a total of three columns - see below for

how it looks before we make all proportions equal :-

===================================================================================================================

Okay, the rows and columns look 'about' right BUT, it is better if we go into the script and change the numbers

to make them exactly equal - see below :-

==================================================================================================

And before we build and run we can set the attribute on the grid to show the grid lines - see below :-

====================================================================================

After selection of the attribute name, choose a value of 'True' and after building and running your should

see something like the following :-

====================================================================================

In need of a 'Frame !? :

It looks to me as if we are in need of a suitable Border element.

Remember from the WPF work you may have done, that the easiest way to put a Border around the Grid

is to use the XAML text editor and place start and end tags before and after the Grid lines.

"Things within Things" ! Let us do that now, place the cursor before the start Grid tag :-

===============================================================================

After selecting the Border item, type in a closing brace (or chevron symbol) to get the following :-

============================================================================

Then highlight and drag the closing tag to after the closing Grid tag as follows :-

============================================================================

Now rearrange the script text, or format it as you require :-

Just in case you don't know, or have forgotten, a section of highlighted text can all be moved in one 'block' or go,

by pressing the tab key to move it to the right (one press of the key for each tab move) or indeed 'Shift+Tab' to

move it back again one tab per press.

Her is the state of the text before I move it :-

==============================================================================

Improving the Border - setting Properties :

Let us now set the border thickness and also the brush colour - see below :-

==============================================================================================

If before we run this we change the root to the fixed mode option we then get this at runtime :-

On the other hand we can use the graphics surface to allow us to click and adjust with the mouse the

Border and Grid elements to not be extended the whole way to the edge and we get a different view

when we set the root to Auto size and then build and run :-

=======================================================================================

Adding some finishing touches :

It would now appear that what we need are a few simple controls to finish off our simple first Silverlight app.

How about a couple of Labels and a couple of Buttons, and maybe within a 'StackPanel' too ;0)

If we then snap these (or fix them) within the grid's cells we can the hide the lines at display time.

So here goes .....................

Below I have simply used the few skills I have picked up while going through the WPF eNotes, it is the XAML

editor, and the Designer in general which has done all the work !

Here is what I have added :-

============================================================================================================

And before I say the runtime display I have made sure that the Border is attached to the side of the Grid, otherwise the

effect at run time is silly I feel :-

==================================================

So we need to add a couple element combinations similar to above, and then we are done.

===============================================================================================================================

Lets see what it looks like - checkout the following :-

Okay, that is it for now, I need to eat my tea - had enough of this success in Silverlight for one afternoon ;-)

We need to upload this to the new web site and make ClickStartExec2 have a live link to run it over the internet.

Good luck with your projects and XAML, see you in the next section ..............

PHH - 20th. January 2011


Adding some Events and Handlers

Before we can see how to add events to respond to, and handlers to then do as required, we need

a suitable app to work with.

I will use as a basis the first trivial app I posted on my website, before I started these eNotes, and then

add the event 'stuff' to this.

First of all we need to make a new project - add this to our existing solution.

So right click in the solution item line in the SE pane, and the use the context menu options of 'Add' ...

'New Project ...'

Provide a title of 'FirstTrivialEG' ... (EG for example in English) ... and then make this new project the 'StartUp'

project as shown below :-

=================================================================================

If you have done everything right the heavy (bold) font should show on this project as in the following image :-

========================================

The next thing I did was copy over the XAML script section which was between the 'Grid' start and end tags, from

my earlier example (EG) that I posted on my new website.

The new project now looks like this :-

====================================================================================================================

If I build and run the solution, we get the 'FirstTrivialEG' project to run and show in the Browser, this is just a check

to see that what we have done all hangs together.

Here is what I now get on screen :-

None of the four buttons has any 'event' functionality - none of them respond as yet to a mouse click.

Okay then guys, we need to try and add an event and handler to the fourth button - the one at the bottom

of the purplish coloured StackPanel - it is the red one.

If we move the cursor into the region which is for the attributes and values of this button, and type 'cl' we

see the following in our XAML editor :-

=====================================================================================================

After selecting 'Click' we get the value to fill with a meaningful method name (yet to be created) for the handler.

Here is how it looks :-

=================================================================================================

I have supplied a suitable name, as well as a 'ClickMode' attribute - see below :-

==============================================================================================

You may be surprised that we have used and set the 'ClickMode' attribute, but it will come in useful at a later stage

in these notes so we are wise to view the option list below :-

===========================================================================

As you can see from the image above, we can have three modes - as you may have expected really.

If we try to build and run at this stage we get the following error message :-

===========================================================================================================================

Yep! quite simple, we have not as yet made a handler method called 'myFirstClick'.

So that is what we must do now. let us look at the dotNet code 'behind' that we currently have.

It is in C# but that does not matter much as it is VERY similar to the Vulcan code we will be able to use in future.

Here is what we currently have :-

===================================================================

As you can see we have only one simple method, so we need to add another.

Let us first of all add the correctly named and formatted (correct syntax) 'blank' method, to see if we can build OK.

Look at the following image for this blank method :-

=============================================================================

And yes, it builds and runs, but nothing appears to happen when we click this fourth (lower) button.

We need some action code - see below :-

=========================================================================================

And now when we build and run, and then click the lower push button, we see the following :-

If you look carefully you will see we have caused the second button to have its text content as well

as foreground colour changed.

At this point it will be instructive to us to have a more thorough look at the details shown in the Output

pane below the XAML script editor - see below :-

=========================================================================================================================================================

I think this basically mean that the '.xap' file is being made, and that it contains the '.dll' and the XAML manifest.

Obviously the '.dll' must be created first.

This is why we don't need to copy the '.dll' file as well - when we place the required files onto a website - into a selected folder.

Obviously we will need to find a better way to run our Silverlight apps than through a 'TestPage' html file, but

Oh! and the TestPage and XAP will work if used from any folder, local or otherwise - as long as the file 'pair' is together.

Finishing off this Section :

I think it would look nice if we changed the string content on the event button itself, as well.

In order to get the following display after the button click - see below :-

We need to make a code behind change as shown :-

===========================================================================

As an exercise for you, go and add two further small changes, in the event handler method change the first button

content from 'Welcome' to 'Hello', and the third button contents to 'Goodbye!'.

Good Luck.

See you in the next section ............

PHH - 28th. January 2011.

Addendum :

Let us take this chance to see a 'MessageBox' - when we click the Button a second time.

Below is what we get at runtime :-

And here is the amended code behind to cause this to happen :-

====================================================================================================

The function of the 'MessageBox' class is just one of the things we will need to become familiar with from the list

of small differences between WPF and Silverlight.

To help us learn these changes, here is what the C# editor intellisense had to say when I coded it just there now :-

======================================================================================

===================================================================================================================

============================================================================================================================================

Obviously, we will get to know this class much more as we get more experienced, and try different things out.

Go and give it a try ;-)

See you in the next section ..................

[ ... this Silverlight app with TestPage will be posted on 'ClickStartVulcan2.net' as "FirstTrivialEvent" ... ]


working script and code

==================================================================================

<UserControl x:Class="FirstTrivialEG.MainPage"

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

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

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

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

mc:Ignorable="d"

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

<Grid x:Name="LayoutRoot" Background="Teal">

<Border Name="myBorder" BorderThickness="3"

BorderBrush="Crimson" Width="180" Height="164" >

<StackPanel Name="mySP" Background="Thistle" Width="180" Height="164">

<Button Height="23" HorizontalAlignment="Left"

Name="pbOne" VerticalAlignment="Top" Width="87" >

Welcome

</Button>

<Button Content="- to -" Height="23" HorizontalAlignment="Center"

Name="pbTwo" VerticalAlignment="Top" Width="87" />

<Button Content="Silverlight 4" Height="23" HorizontalAlignment="Right"

Name="pbThree" VerticalAlignment="Top" Width="87" />

<Button Visibility="Visible" Height="29" Width="0"/>

<Button Content="[ 'Click Start 2' ]" Height="23"

Name="pbClickStart1" Width="114" Background="Red">

</Button>

</StackPanel>

</Border>

</Grid>

</UserControl>

==================================================================================

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;

namespace FirstTrivialEG

{

public partial class MainPage : UserControl

{

public MainPage()

{

InitializeComponent();

}

void myFirstClick(object sender, RoutedEventArgs e)

{

string cCont = (string)this.pbClickStart1.Content;

if ( cCont == "> clicked - done ! <" )

{

MessageBox.Show("Already clicked ...", "REPEAT !?", MessageBoxButton.OK);

}

//---------------------------------------------------------------------------

SolidColorBrush scb = new SolidColorBrush(Colors.Green);

SolidColorBrush scb2 = new SolidColorBrush(Colors.Orange);

this.pbTwo.Background = scb;

this.pbTwo.Foreground = scb2;

this.pbTwo.Content = "my first event !";

this.pbClickStart1.Content = "> clicked - done ! <";

}

}

}

==================================================================================

<UserControl x:Class="FirstTrivialEG.MainPage"

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

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

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

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

mc:Ignorable="d"

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

<Grid x:Name="LayoutRoot" Background="Teal">

<Border Name="myBorder" BorderThickness="3"

BorderBrush="Crimson" Width="200" Height="164" >

<StackPanel Name="mySP" Background="Thistle" Width="194" Height="164">

<Button Height="23" HorizontalAlignment="Left"

Name="pbOne" VerticalAlignment="Top" Width="87" >

Welcome

</Button>

<Button Content="- to -" Height="23" HorizontalAlignment="Center"

Name="pbTwo" VerticalAlignment="Top" Width="87" />

<Button Content="Silverlight 4" Height="23" HorizontalAlignment="Right"

Name="pbThree" VerticalAlignment="Top" Width="87" />

<Button Visibility="Visible" Height="29" Width="0"/>

<Button Content="[ Click me - see an event ]" Height="23"

Name="pbClickStart1" Width="170" Background="Red"

Click="myFirstClick" ClickMode="Press">

</Button>

</StackPanel>

</Border>

</Grid>

</UserControl>

==================================================================================

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

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

x:Class="FirstTrivialEG.App"

>

<Application.Resources>

</Application.Resources>

</Application>

==================================================================================

PHH - 29th. January 2011.


Tooltips the Silverlight way

With WPF forms we can have a Tooltip property on many controls and the Button class is just one

of these as can be seen below :-

==============================================================================================================

So if we complete the attribute and its value as shown below :-

=======================================================================================

Then at runtime the WPF applet looks like the following when the mouse pointer is moved over the control :-

======================================================

However, in Silverlight 4 things are different to the WPF situation. Simply let us try to add an attribute to a SL button

and see what we get on offer - see below :-

=================================================================================================================

As you can see in the image above there is no ToolTip attribute on offer, so we have to use the ToolTipService. This same

class is available in WPF, which is interesting to know, and so the approach of using it in place of the WPF standard property

would appear to work with both.

Let us see one way to script this, study the syntax in the image below :-

==============================================================

For the moment we will 'hard script' each of our buttons so that they have a section similar to that shown above, a

'ToolTipService' section - or object.

Here is the working script shown in the following image :-

==============================================================================================

And we can now study some of the runtime results - checkout the following images :-

Notice that I have had to make the previously 'invisible' button VERY narrow so that I could bring up the tooltip

at runtime - when the width was set to zero it would not show.

Just to inform you, I did make an adjustment in the script so that the display was better, I changed the vertical

'off-set' to 10 from 20 - so it does not look so detached.

The Future !? :

When we get more knowledgeable and more experienced we may well be able to use a Resources section and script

entry to lessen the script required in the hard scripting used above.

For now let us move on to the next section - but only after we study the following script in which we have had to embed

a special character within the string we wish to output in our Tooltip message.

Study the following carefully :-

===============================================================================

Notice that to place ' < ' within the string we need to use ' &lt; ' as a complete group. And don't let your eyes miss the semi

colon ' ; ' since it is important.

Below is a full list including something relating to the commenting of script. Note this applies to XAML and hence WPF

as well as Silverlight.

=================================================================================================================================================================

See you in the next section .........

PHH - 28th. January 2011.


Colors - limitations for Browser ?

==============================================================================================================================================

=======================================================================================================

PHH - 28th. January 2011.


Chapter 2 - running from a Web Site

Type of Website :

You can't run Silverlight apps from what was/is considered a 'normal' website.

The ones from a year or two again said they supported PHP and MySQL - these are of no use to us for SL.

It is possible to get more modern websites which use supporting technologies of ASP.net, Silverlight and MSSQL.

Yes, that is Microsoft's SQL server 2008 and R2, so the site is a Windows site and not a Unix one. Or some part

of it is - the part that affects us.

I will say more about finding a suitable site and how to go about making it fit for regular use in a following subsection.

What is Required :

This is quite straightforward, and if we are running the template in such a way as to make 'Local' files, and not automatically

upload to a specified website, we simply need two which are created for us as build and run time.

Study the image bellow to see the '.xap' (said zap) and '.html. files. Apparently the '.dll. is rolled into the '.xap' and so is not

required - see below :-

=================================================================================================================================================================================================

If we copy these two files to a web folder and then in a calling HTML page have a link to the test page 'html' file, then the

Silverlight app will be made to run in the browser.

PHH - 28th. January 2011.


Finding a suitable Host / Provider

PHH - 29th. January 2011.


Setting up a New Website

PHH - 29th. January 2011.


Copying and Placing SL files

PHH - 29th. January 2011.


What is in the '.html' file

If you are interested (not required to make things just work) you can study the content of the auto-generated

HTML file.

This apparently just runs the "ClickStart2.xap" file and I have made this blue in the script below.

The first part of the script is about setting up and running the Java script if an error was to occur in the XAML or

Silverlight 'stuff'.

==============================================================================================

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

<!-- saved from url=(0014)about:internet -->

<head>

<title>ClickStart2</title>

<style type="text/css">

html, body {

height: 100%;

overflow: auto;

}

body {

padding: 0;

margin: 0;

}

#silverlightControlHost {

height: 100%;

text-align:center;

}

</style>

<script type="text/javascript">

function onSilverlightError(sender, args) {

var appSource = "";

if (sender != null && sender != 0) {

appSource = sender.getHost().Source;

}

var errorType = args.ErrorType;

var iErrorCode = args.ErrorCode;

if (errorType == "ImageError" || errorType == "MediaError") {

return;

}

var errMsg = "Unhandled Error in Silverlight Application " + appSource + "\n" ;

errMsg += "Code: "+ iErrorCode + " \n";

errMsg += "Category: " + errorType + " \n";

errMsg += "Message: " + args.ErrorMessage + " \n";

if (errorType == "ParserError") {

errMsg += "File: " + args.xamlFile + " \n";

errMsg += "Line: " + args.lineNumber + " \n";

errMsg += "Position: " + args.charPosition + " \n";

}

else if (errorType == "RuntimeError") {

if (args.lineNumber != 0) {

errMsg += "Line: " + args.lineNumber + " \n";

errMsg += "Position: " + args.charPosition + " \n";

}

errMsg += "MethodName: " + args.methodName + " \n";

}

throw new Error(errMsg);

}

</script>

</head>

<body>

<form id="form1" runat="server" style="height:100%">

<div id="silverlightControlHost">

<object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">

<param name="source" value="ClickStart2.xap"/>

<param name="onError" value="onSilverlightError" />

<param name="background" value="white" />

<param name="minRuntimeVersion" value="4.0.50826.0" />

<param name="autoUpgrade" value="true" />

<a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=4.0.50826.0" style="text-decoration:none">

<img src="http://go.microsoft.com/fwlink/?LinkId=161376" alt="Get Microsoft Silverlight" style="border-style:none"/>

</a>

</object><iframe id="_sl_historyFrame" style="visibility:hidden;height:0px;width:0px;border:0px"></iframe></div>

</form>

</body>

</html>

=================================================================================================

I would imagine that the 'TestPage' file is almost identical for each SL project app., and that only the filename changes.

But I am on thin ice, as I know virtually nothing about this side of Silverlight.

No doubt we will find out more as we explore and research ;-)

See you in the next section ................

PHH - 29th. January 2011.


How to get SL apps to run

PHH - 29th. January 2011.


about Client Browsers

PHH - 3rd. February 2011.


Chapter 3 - going a little further

PHH - 29th. January 2011.


List Controls

In order to study simple lists in Silverlight we need to close any existing solution and project and

create a new solution called 'ListControls'.

Do this now so that you can follow along with me when we get to adding XAML and form elements.

Here is what my new solution looks like in the VS10 shell :-

===============================================================================================================================================

We can now use this solution to explore both ListBox elements as well as ComboBox controls.

It is probably best to leave this short subsection as it is and move on directly to the next section where

we will look at ListBoxes and their simple use.

See you in the next section .........

PHH - 29th. January 2011.


Listbox

Okay you guys, let us get our sleeves rolled up and get right into some scripting.

First a bit of drag and drop, see the image below where we drag a 'ListBox' from the Toolbox onto

the graphical design surface :-

===========================================================

The result of dropping the selected item at the shown mouse pointer position is shown in the

following image :-

=====================================================================================================

The above image shows the script for the ListBox element, and we need to change this so that we have a

full closing tag, and this will give us room to add in list items.

Move the cursor to the closing slash ' / ' and brace ' > ' and highlight the pair of characters like shown below :-

============================================================================

Now simply press the 'Delete' key and type a closing brace ' > ' and you should see this below :-

=================================================================================

The cursor ought to be flashing between the two tags, so simply press the enter key go get this :-

===============================================================================

In the space created - line 13 - add a 'ListBoxItem' object to the script by manually typing and using the intellisense :-

=========================================================

Look at the results of my entry shown below - then you copy it :-

======================================================================================================

Now simply add a few more script lines to increase the number of ListBoxItems.

I am hoping to make a simple app which shows the possible DevShare 2011 session presenters, as well

as the hopeful attendees - so that is the reason for the particular names.

Here is what we have so far :-

==================================================================================================

And now its about time we did a build and ran the app - here is what our efforts to date look like :-

We may also have a contribution from Lewis Todd and/or his colleague, but that is not really the point at the moment.

In the process of adding a Label so we can have a heading, and then giving it some colour, I got a reminder that we

ought to take care - note that we MUST leave at least one space between the last value and the next attribute - see below :-

=================================================================================================

Adding the extra space makes the 'nasty' wavy blue line disappear ;-)

Now let us investigate the border properties for both the Label and LisBox elements in Silverlight.

The following is the display result at runtime :-

And now we need to view the script to see what changes brought this about - see below :-

Notice the two 'Border' entries in the intellisense list above.

It may interest you (as much as it does me) that these two properties (attributes) exist for the ListBox element and

also for each in WPF as well. So some controls do have their own border as such - we don't have to add a Border element

to everything ;-)

Here is the full script shown below :-

==================================================================================================

So adding a few more elements and details, with similar attributes and values, we end up with this :-

And the FULL script is included in the 'working script and code' section which is a child folder to this one.

Time to move on and try and get some events working etc. etc..

See you in the next sections ......

PHH - 29th. January 2011.


working script and code

=========================================================================================

<UserControl x:Class="ListControls.MainPage"

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

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

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

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

  mc:Ignorable="d"

  d:DesignHeight="300" d:DesignWidth="400" xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">

  <Grid x:Name="LayoutRoot" Background="AliceBlue">

      <ListBox Height="199" HorizontalAlignment="Left"

              Margin="12,61,0,0" Name="listBox1"

              VerticalAlignment="Top" Width="147"

              Background="BlanchedAlmond"

              BorderThickness="2" BorderBrush="Red">

          <ListBoxItem Content="Willie Moore"/>

          <ListBoxItem Content="Mike Pitcher"/>

          <ListBoxItem Content="Alwyn Jennings-Bramly"/>

          <ListBoxItem Content="Dave Francis"/>

          <ListBoxItem Content="Nick Friend"/>

          <ListBoxItem Content="Pam Pitcher"/>

          <ListBoxItem Content="Bev Francis"/>

          <ListBoxItem Content="Phil Hepburn"/>

      </ListBox>

      <sdk:Label Height="23" HorizontalAlignment="Left"

                Margin="12,12,0,0" Name="label1" VerticalAlignment="Top"

                Content="Session Presenters :" Width="147"

                Background="BlanchedAlmond" Foreground="Maroon"

                BorderThickness="2" BorderBrush="Red"/>

      <sdk:Label Height="23" HorizontalAlignment="Left" Margin="209,14,0,0"

                Name="label2" VerticalAlignment="Top" Width="147"

                Background="Cornsilk" Foreground="Crimson"

                BorderThickness="2" BorderBrush="Red"

                Content="Event Attendees :" />

      <ListBox Height="227" HorizontalAlignment="Left" Margin="209,61,0,0"

              Name="listBox2" VerticalAlignment="Top" Width="147"

              Background="Cornsilk" Foreground="Crimson"

              BorderThickness="2" BorderBrush="Red">

          <ListBoxItem Content="Chris Pyrgas"/>

          <ListBoxItem Content="Dan Logan"/>

          <ListBoxItem Content="Peter Guetens"/>

          <ListBoxItem Content="Dennis"/>

          <ListBoxItem Content="Neale Robinson"/>

          <ListBoxItem Content="Lewis Todd"/>

          <ListBoxItem Content="LT's mate"/>

          <ListBoxItem Content="Mike Bertenshaw"/>

          <ListBoxItem Content="Dai Darkins"/>

      </ListBox>

  </Grid>

</UserControl>

=========================================================================================

PHH - 29th. 2011


Combobox

PHH - 29th. January 2011.


Chapter 4 - Popup, ChildWindow or MessageBox

Quite often in our solution functionality we need to bring some information to the attention of the user,

or maybe have then provide a small amount of input data.

While they focus on the content and/or input we don't wish them to be doing anything else on the main

form.

We can use three simple ways to do this, some simpler than others.

The MessageBox is the simplest, but it can be displayed by the operating system so that it is outside of the

bounds on the calling window, or form.

Both Popup and ChildWindow solutions seem to look more professional (if done correctly) but of course they

need a little more work done by the developer / programmer.

Before we move into the subsections to see how this is done in detail, examining the XAML script and looking

at the dotNet code (C# or Vulcan), let us see what these look like when displayed.

First the 'MessageBox' :-

And now the Popup :-

============================================================================

[ .. the left mouse button click brought up the Popup, the right brings up a ChildWindow .. ]

Finally the 'ChildWindow' :-

[ .. notice how the ChildWindow may be moved (dragged) but no part of it appears outside of the Browser .. ]

Going 'Message Crazy' !? :

And of course we can go message crazy, or silly, by having all three open at once from one small app - see below :-

Now go to the subsections of this chapter to see how this is done in XAML script with C# dotNet code.

See you there ...........

PHH - 30th. January 2011.


MessageBox

PHH - 30th. January 2011.


Popup

It is probably just as well to display here what the SDK documentation has to say on the matter of Popups.

However, it is easier to get some positive results that the text may indicate while reading it for the first time.

=============================================================================================================================

There is also an issue with which we may need to deal - and we certainly need to know about it :-

========================================================================================================================

And finally, just a bit more information :-

========================================================================================================================

Our Own Example of Popup :

And now we need to explorer this element for ourselves.

For this first working example of our own I am taking some sample code from the SDK docs so that we have a

working example to play with, and then adapt and improve.

Before we add a section to our solution / project called 'PU_MB_and_CW' we will add a popup to the 'ListControls' app

we got to work for us in a previous chapter.

Study the details in the image shown below :-

============================================================================================================

Obviously, we need to have an event suitably selected in our XAML script so that the handler methods gets fired.

Here are the event 'set' for the Grid in our "ListControls" main page, one for the Popup and one for the ChildWindow.

Study the detail carefully :-

================================================================================================

You need to realise that the handler method 'myShowScript' is associated with a ChildWIndow, on which I intend to

get around to showing the XAML script (and dotNet code) for the app itself. This way an interested reader of 'ClickStartVulcan2.net'

can see the detail which makes the app function.

Enough of that, and back to the fun stuff.

It is important that we don't forget a few smaller details which are shown in the next image - see below :-

=================================================================================

We have declared 'p' as a class variable, as well as creating our own 'Initialize()' method.

So we create a class wide Popup object at the time of initialising. We then just use it.

[ ** note ** the collapsed sections have to do with the 'ChildWindow' and are not relevant for this Popup discussion .. ]

Before we move on, let us see what happens when we change the 'Offset' values by 100 units each - see below :-

===========================================================================================

See how the Popup has move at 45 degrees down and to the right on the main page.

Doing more with the Settings of the Popup :

First of all let us try to add more text so that we need to handle long lines, and include a line feed, or new line character

within our text.

Remember we can still use the escaped text approach - see below :-

======================================================================================================

In the above image notice that the '\n' character combination cause a new line to be started after the 'XAML' in

out text string.

PHH - 30th. January 2011.


ChildWindow

MainPage.xaml :

==================================================================================

MainPage.xaml.cs :

=======================================================================================

LoginWindow.xaml :

==================================================================================================

LoginWindow.xaml.cs :

===================================================================================================================

PHH - 30th. January 2011.


ContextMenu

When I started to compile these eNotes, and was at the very beginnings of my research into Silverlight,

it appeared as though there was neither a menu nor a context menu in the toolbox. I assumed that these

would follow along - BUT - had no proof of this idea !

However, this morning while looking into the Silverlight Toolkit I have spotted the entry of a 'Context Menu' as

well as a 'ContextMenuService' class.

=============================================================================================================

===============================================================================================================

Note that at this moment in time (before Silverlight 5 beta is released in May) the two classes above are at the 'Preview'

status level.

this means we may well see changes in the classes when they are finally released to the public - so don't use them

too extensively before that.

I do suggest we have a quick look at what these classes may have to offer us however.

Because the notes in the SDK are 'brief' to say the least, I have Googled and found a useful article on which to base

some demo and test work. Details of the article are as follows :-

Walter Ferrari - May 05th. 2010 :-

http://www.silverlightshow.net/items/Anatomy-of-the-ContextMenu-how-it-is-made-how-to-use-it-and-how-to-abuse-it.aspx

Just be aware that Walter may take things a little too far since the real Microsoft tolls will be out soon, and work differently

once we take them beyond the basic level of functionality.

Here is what the SDK notes for the CHM toolkit file say :-

===========================================================

And after selecting the 'ContextMenu' class we see this below :-

[ .. note this is just the start of what is available .. ]

======================================================================================================

According to the SDK notes we need to reference the '......Input.Toolkit' 'dll' as follows :-

========================================================

And that also means we need to add a line at the top (start) of our XAML script too - see below :-

==============================================================================================================

If you have installed the Silverlight Toolkit and included the right script and code lines, you will have an entry in the

Toolbox pane like that following :-

====================================================================================================================================

In the images shown above we can see a real bunch of new Toolbox entries which have originated in the 'Toolkit'

download.

Check the names against the Tree view pane of the CHM notes - a portion of which is shown below :-

[ The parent of these is 'System.Windows.Controls Namespace' ]

================================================================

Let us now look at how we may add some extra functionality to one of our test apps.

Below is the first OOB test app where I am experimenting with 'Out of Browser' behaviour.

Now that we have the correct namespace entries at the head of our XAML script section, we get suitable intellisense

behaviour in the editor.

The following code shows a context menu added to the stack panel enclosed in the red border, the one containing the

three bell images. Note the object script lines have a 'toolkit:' prefix showing :-

==========================================================================================================================================================

Also notice in the above image that the small bell icon is due to the inclusion of an Image with a source file of

'Images/Iconbell_16.png'.

So basically, we have added three menu items to our context menu - the one which now displays when we

right click anywhere within the three bells 'area'.

However, we can push the class a little bit further, and get a submenu by a little bit of 'fiddling' around.

See below for the start of a submenu which is associated with the fourth main menu item :-

===========================================================================

The XAML script responsible for the above behaviour is listed below :-

===================================================================================================

Obviously, if we are to get menu functionality, we need to provide each menu item and submenu item with a

name, as well and associating the 'Click' event with and event handler method.

Below is the working app after suitable script changes :-

And now we can see the script / code, and the required changes in the following two images :-

=====================================================================================================================

=======================================================================================

If we also wish to try and make our personalised context menu a little more like that we are used to,

we can add an extra item which acts as a Expand/Collapse toggle button - see below :-

============================================================================

Clicking what feels like the item 'header' allows us to see and hide the items after the first one.

Checkout the following :-

The change to the XAML script looks as follows :-

And the code behind now has the following entry to handle the toggle action :-

====================================================================================

This is all a bit of fun, and allows us to demonstrate our new found XAML and Silverlight skills - BUT - we must

remember to NOT take this too far because we will most definitely see some changes when the full version of the

menu classes are released to the public.

Meanwhile, have some fun ;-)

PHH - 6th. February 2011.


the PU_MB_and_CW project

The title of this subsection, along with the VS solution, simple stands for :-

"PopUp_MessageBox_and_ChildWindow" project.

[ .. even though it is Popup and not 'PopUp' ! .. ]

Making a Start :

Open up VS10 and then close all solutions and projects that are open.

Start a new Project/Solution entitled "PU_MB_and_CW" after selecting the C# Template for a Silverlight

Application, and you should get in your SE pane what is shown below :-

The main part (central section) of your design area will also look like the following :-

=========================================================================================================

Not a lot to show, but a good start ;-)

Now lets move on and get some results.

Adding elements to the main page :

Before we can meaningfully add any of the message type functionality / elements (MB, PU or CW) to our main page,

we need to add some basic controls.

Let us first of all add a 'TextBox' to our main page by dragging one from the Toolbox - see below :-

===============================================================================

Which finishes up like this :-

=================================================================================

** note ** I have formatted the attributes to make them clearer - and - not to stretch off too

far to the right hand side of the screen. You may like to do the same.

If you build and run (to see if there have been any errors introduced) you hopefully will see the

following rather dull and uninspiring browser output ;0)) See below :-

Also we need to get used to checking the Output pane, which looks like this for me here :-

===================================================================================================================

The only issue is the long filepath for the '.dll' which is completed from the 'Projects' folder below :-

===========================================================================

If we now look in the folder with 'WE' (Windows Explorer) this is what we see :-

=========================================================================================================================================================

Before I add any more elements we can adjust a few attributes which at the moment are set

at default values.

Here is what now contains all the working (and changed) script to date :-

=======================================================================================================

Notice once again that the 'TextBox' control is one which has its own border setting, we don't need

a separate element.

Now select from your toolbox a 'Button' and a 'PasswordBox' control, sliding them into place on the graphical design

surface using the red guides to line them up with what is already on the form.

You should aim to get something like the following :-

================================================================================================================

Check that your app still builds and runs - this one is OK !

When adding more controls make sure you use the inbuilt alignment facilities - check below

to see the addition of more controls :-

[** note 8** fuller details of these are displayed even further down the page of these notes ..]

=============================================================================================================

And now to make the last big effort with adding controls and adjusting their attributes, before we build into our

solution/project some event handling, which will then cause MB, PU and CW to be displayed.

Look carefully at the following image and copy the new code, as well as changing the names of some earlier

elements - checkout the image below :-

[ ** note ** the changed names for the elements are shown in parentheses after the nested items in the DO pane .. ]

=============================================================================================================

Make a special note of script line 35, the way the text string grouping of '&amp;' represents what is

eventually displayed ' & '. Other combinations were shown in an SDK docs list previously in these eNotes.

[ Chapter one, Tooltips .... section ]

In the image above, once again it has to be realised that I have done a lot of test tidying or formatting. It just makes

it much easier to read and follow - but will work without it, if you must :((

I have built and run my version of this app, and here is what I get after some sample test input data :-

And NO ! I will not tell you the password - you will have to wait till we add the event handlers which

will launch the 'MessageBox', Popup, or 'ChildWindow' elements.

Before we move on to add the interactivity, let us see what the date and time controls look like when

used to select their respective values - see below :-

======================================================================

and now the time picker :-

======================================================================

Now that we have had a taste of some new controls to us in Silverlight, let us move on to data input and selection,

and then display of this on screen in some form or another.

Displaying some Input Details :

Let us start simply, below is shown the details of the 'TextBox' control displayed in a 'MessageBox' when the correct

button has been clicked - here we use the 'Display Text' button :-

============================================================

And, if we make it slightly 'clever' we can detect either not data entry, or an 'empty' condition :-

============================================================

First of all we need to include an attribute which is the 'Click' event - see below :-

==================================================================================================

Remember we can tell event in the intellisense list by the yellow lightning symbol - see the following example :-

===================================================================

And to accompany this newly added event, we now need to add a dotNet method in the code behind to handle what

happens when the click event fires, on the 'Display Text' button.

Here is the smarter of the methods I have tried this morning :-

=======================================================================================================

Popup for the 'PasswordBox' control :

Now to handle the display of the content of the 'PasswordBox' element we will use a Popup, just to be different.

If we first create a handler method before selecting an event for the 'See Password' button, we will witness some new

and interesting behaviour at the time we come to use the intellisense for the selection of an event name.

So let us drop into the dotNet code behind and add a suitable handler method. Notice that to start with we will

use a 'MessageBox' output, just until we have the interactive response checked out, then we can alter things to do

a Popup instead.

Here is what I have done at my end of things - this is a working dotNet method :-

=============================================================================================================================

Now we can see why we have done the method handler creation first - let us now try and add an event to our

XAML script for the 'See Password' button - study the following carefully :-

==============================================================================================

You will notice in the above image that the design system - through the context aware intellisense - offers a list of

two suitable already created methods, as well as an option to create a new one.

If we had chosen the new one, we get a default name in script, and a stub method in code behind - see below :-

================================================================================

======================================================================================

And out of interest, if we tried to add the event to the button attributes now, we would have a third option added

to our list of existing possible methods - see below :-

===============================================================================

Okay then guys, what does our MessageBox have to say - lets test it before we move on to add the Popup instead.

Here is what I get :-

=============================================================

and with not sufficient data entered we get :-

================================================================

Just before we move on to change over to the Popup, we can add a 'ClickMode' attribute and select 'Hover'

which means that 'mouse over' will fire the method and not a mouse click :-

================================================================================================

You will have to trust me folks - it does work as required - just move the pointer over the button, and a

MB shows up nicely :-

============================================================

What Changes are Required ? :

Before we study code, let us see what we have caused to happen by making these changes :-

===============================================================

==========================================================

[ I have to confess that I needed to change the 'ClickMode' back from 'Hover' simply because it seemed a bit 'sticky'

for me on my software platform - I did not say it didn't work correctly - BUT - I did not like it :((

The mode set at 'press', which I assume the default is when the attribute is removed from script altogether, seems to

operate as I would expect it to - so we will stick with that for now. ]

-

ere is the dotNet code we need 'behind' :-

-*

6- [image] -

========================================================================================================

The above code seems to work nicely, and we can worry about making 'User Controls' another day ;-)

For now let us move on to make a 'ChildWindow' (CW)and show it as a response to clicking the 'Date & Time' button.

On this CW we will display details of the select date, as well as the chosen time.

Date and Time 'ChildWindow' :

Before we get to make a 'ChildWindow' and populate it in some way with suitable data about our choice of Date

and Time using the selection controls, we need to handle correctly the controls themselves, so we extract the

correct data values, and also don't cause runtime errors.

Below is a simple example where the event of selecting a time value from the list causes a suitable message

to be output in a simple 'MessageBox'. Study the details shown :-

==================================================================

And then we have another event and its associated handler are trapping the newly entered date just as the control

is closing - study the details below :-

==============================================================================================================================

Script and dotNet Code required :

It is now interesting to see what we need to add to the XAML script, as well as the code behind, in order

to make our app function in a safe and robust way.

Let us first examine the 'DatePicker', here is the script entry - see below :-

===========================================================================================================

Highlighted is the extra text which associates the event called 'SelectDateChanged' and then this event

will call the method 'myDateChanged' - see below for the dotNet code :-

=========================================================================================

Notice that in the image above we can see a Boolean class variable 'lDchange' which tracks whether a value

has been chosen. This prevents possible errors in our display method code, and this is clearly shown in the

following image :-

==================================================================================================================

The above code is only part complete in a few ways, BUT, it does prevent runtime errors when an attempt at displaying a

'no selected' value is being attempted. I know I had the error not long back this morning ;-)

The accompanying code to make this work looks like this :-

================================================================

We know that if the Boolean value is TRUE then there must be a selected, chosen, or set value, and so it can be

displayed.

In the following image we can see the script line where the event has been added for the 'TimePicker' - see below :-

==========================================================================================================

So the event called 'ValueChanged' which is one of the events available on the 'TimePicker' object, needs an event

handler method called 'myTimeChanged'.

In the following image we can see the handler method code for the this :-

===========================================================================================================

Notice I have left in place, and commented out, a couple of lines of code which show that I tried an interim procedure

of 'MessageBox' output, and also explored an alternative way to pick up the new value.

You may like to see what other options are in the intellisense list for 'e' in this method - see below :-

=============================================================================================================================================

Final Improvements :

Okay then you guys, let us make our final improvements.

Let us upgrade the performance of our 'Display' method. In the following images we can see the runtime

results of the improvements :-

===========================================================

And now the time value ..... :-

==========================================================

The code to do this is now shown below - not much different, but a better overall performance ;-)

=======================================================================================================================

Also after a short time adjusting a few cosmetic details we see the following output :-

Time to move on I feel.

I was going to place details of the Date and Time data in a 'ChildWindow' (CW) but we have enough in this section already.

It would make sense therefore to have a separate section as a subsection, within the previous section on CW. So if

you have not already seen and studied this, go to the previous section and see how it is done. It is at the end of the section,

after the general stuff.

Let us go to the next section and learn some more things about events and the handling of them in code.

See you in the next section ................

PHH - 30th. January 2011.


working script and code ...

=====================================================================

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;

//-----------------------------------

using System.Windows.Controls.Primitives;

namespace PU_MB_and_CW

{

public partial class MainPage : UserControl

{

private Popup p;

private Boolean lDchange, lTchange;

//-------------------------------------

public MainPage()

{

InitializeComponent();

this.Initialize();

}

void Initialize()

{

lDchange = false;

lTchange = false;

}

void myTBdisplay(object sender, RoutedEventArgs e)

{

string cMess = this.myTBmessages.Text.Trim();

if (cMess.Length < 1)

MessageBox.Show("PLEASE type some content !?", "TextBox 'Empty' :",

MessageBoxButton.OK);

else

MessageBox.Show(cMess, "TextBox 'stuff' :", MessageBoxButton.OK);

}

void myPWdisplay(object sender, RoutedEventArgs e)

{

string cMess = ((string)this.passwordBox1.Password).Trim();

string cText;

if (cMess.Length < 1)

{

cText = "Password appears empty !?\n please enter one ...";

}

else

{

cText = "Please check ... \n Password entered so far is :- ";

cText += cMess;

}

//----- Create the popup object -----

this.p = new Popup();

// Create some content to show in the popup. Typically you would

//----- create a user control -----

Border border = new Border();

border.BorderBrush = new SolidColorBrush(Colors.Black);

border.BorderThickness = new Thickness(5.0);

StackPanel panel1 = new StackPanel();

panel1.Background = new SolidColorBrush(Colors.LightGray);

Button button1 = new Button();

button1.Content = "Close";

button1.Margin = new Thickness(5.0);

button1.Click += new RoutedEventHandler(button1_Click);

TextBlock textblock1 = new TextBlock();

textblock1.Text = cText;

textblock1.Margin = new Thickness(5.0);

panel1.Children.Add(textblock1);

panel1.Children.Add(button1);

border.Child = panel1;

// Set the Child property of Popup to the border

// which contains a stackpanel, textblock and button.

this.p.Child = border;

// Set where the popup will show up on the screen.

this.p.VerticalOffset = 25;

this.p.HorizontalOffset = 25;

// Open the popup.

this.p.IsOpen = true;

}

void button1_Click(object sender, RoutedEventArgs e)

{

//----- Close the popup -----

this.p.IsOpen = false;

}

void myDTdisplay(object sender, RoutedEventArgs e)

{

if (lDchange)

{

string cMess = ((DateTime)this.datePicker1.SelectedDate).ToLongDateString();

MessageBox.Show(cMess, "Date :", MessageBoxButton.OK);

}

else

MessageBox.Show("First select a Date value ...", "Date :", MessageBoxButton.OK);

if (lTchange)

{

string cMess2 = ((DateTime)this.timePicker1.Value).ToLongTimeString();

MessageBox.Show(cMess2, "Time :", MessageBoxButton.OK);

}

else

MessageBox.Show("First select a Time value ...", "Time :", MessageBoxButton.OK);

}

void myTimeChanged(object sender, RoutedPropertyChangedEventArgs<Nullable<DateTime>> e)

{

//Nullable<DateTime> myTime = this.timePicker1.Value;

Nullable<DateTime> myTime = e.NewValue;

Nullable<DateTime> myOldTime = e.OldValue;

string cText = myTime.ToString();

//MessageBox.Show(cText, "New Time :", MessageBoxButton.OK);

lTchange = true;

}

void myDateChanged(object sender, SelectionChangedEventArgs e)

{

string cText = e.AddedItems[0] + "!";

MessageBox.Show(cText, "New date :", MessageBoxButton.OK);

lDchange = true;

}

}

}

=====================================================================

<UserControl x:Class="PU_MB_and_CW.MainPage"

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

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

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

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

mc:Ignorable="d"

d:DesignHeight="380" d:DesignWidth="480"

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

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

<Border Background="AliceBlue" BorderBrush="Maroon" BorderThickness="3" Width="482" Height="385">

<Grid x:Name="LayoutRoot" Height="300" Width="400"

Background="Cornsilk">

<TextBox Height="23" Width="120"

HorizontalAlignment="Left"

VerticalAlignment="Top"

Name="myTBmessages"

Margin="36,48,0,0"

Background="AliceBlue"

BorderBrush="Maroon"

BorderThickness="2"/>

<Button Content="Display Text" Height="23" HorizontalAlignment="Left"

Margin="210,48,0,0" Name="pbTB" VerticalAlignment="Top"

Width="98" Click="myTBdisplay"/>

<PasswordBox Height="23" HorizontalAlignment="Left"

Margin="36,108,0,0" Name="passwordBox1"

VerticalAlignment="Top" Width="120" />

<sdk:DatePicker Height="23" HorizontalAlignment="Left" SelectedDateChanged="myDateChanged"

Margin="36,168,0,0" Name="datePicker1"

VerticalAlignment="Top" Width="120" />

<toolkit:TimePicker Height="22" HorizontalAlignment="Left" ValueChanged="myTimeChanged"

Margin="36,231,0,0" Name="timePicker1"

VerticalAlignment="Top" />

<Button Content="See Password" Height="23"

HorizontalAlignment="Left" Width="98"

Margin="210,108,0,0" Name="pbPW"

VerticalAlignment="Top" Click="myPWdisplay"/>

<Button Content="Date &amp; Time" Height="23"

HorizontalAlignment="Left" Width="98"

Margin="210,196,0,0" Name="pbDateAndTime"

VerticalAlignment="Top" Click="myDTdisplay"/>

</Grid>

</Border>

</UserControl>

<!--ClickMode="Hover"-->

=====================================================================

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

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

x:Class="PU_MB_and_CW.App"

>

<Application.Resources>

</Application.Resources>

</Application>

=====================================================================

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;

namespace PU_MB_and_CW

{

public partial class App : Application

{

public App()

{

this.Startup += this.Application_Startup;

this.Exit += this.Application_Exit;

this.UnhandledException += this.Application_UnhandledException;

InitializeComponent();

}

private void Application_Startup(object sender, StartupEventArgs e)

{

this.RootVisual = new MainPage();

}

private void Application_Exit(object sender, EventArgs e)

{

}

private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)

{

// If the app is running outside of the debugger then report the exception using

// the browser's exception mechanism. On IE this will display it a yellow alert

// icon in the status bar and Firefox will display a script error.

if (!System.Diagnostics.Debugger.IsAttached)

{

// NOTE: This will allow the application to continue running after an exception has been thrown

// but not handled.

// For production applications this error handling should be replaced with something that will

// report the error to the website and stop the application.

e.Handled = true;

Deployment.Current.Dispatcher.BeginInvoke(delegate { ReportErrorToDOM(e); });

}

}

private void ReportErrorToDOM(ApplicationUnhandledExceptionEventArgs e)

{

try

{

string errorMsg = e.ExceptionObject.Message + e.ExceptionObject.StackTrace;

errorMsg = errorMsg.Replace('"', '\'').Replace("\r\n", @"\n");

System.Windows.Browser.HtmlPage.Window.Eval("throw new Error(\"Unhandled Error in Silverlight Application " + errorMsg + "\");");

}

catch (Exception)

{

}

}

}

}

=====================================================================

PHH - 1st. February 2011.


Chapter 5 - Events, responding to more ...

PHH - 28th. January 2011.


Chapter 6 - Chaining Forms

PHH - 30th. January 2011.


Chapter 7 - Silverlight Designer for VS

For this topic let us start with what the SDK documentation has to say :-

==========================================================================================================================

PHH - 31st January 2011.


Design View

=========================================================================================================================

PHH - 31st .January 2011.


XAML View & PP & DO

=========================================================================================================================

PHH - 31st. January 2011.


Chapter 8 - Some useful Controls

Enter topic text here.


Tab

Okay then guys, the following image shows what we are trying to do in our first test app. :-

==================================================================

As we often do, we are taking the SDK documentation example as a start, before we adapt and embellish ;-)

Close down all you open projects and solutions, and create a new one called "TabControls".

As I usually do I have set the checkbox to the local option and also the version of Silverlight to be 4.0 too.

If you do things right you ought to get something like this :-

==========================================================================================================================================================================

If we now go to the 'Common Silverlight Controls' folder (or tab) of the Toolbox pane, we can drag and drop a

'TabControl' element onto the graphical surface and we get something like this below :-

=====================================================================================================================

With this simple act we get a running app (of sorts) and building, and running it we see this :-

However, this is okay for when we do our own creation of new Silverlight apps. but we did say we would

first explore the SDK sample.

So in the script, code and image below I have cut and pasted the sample - Oh! and made a small change

right from the off - more on this in a minute.

For now let us see the results, and then we can work back etc.. Here is the app running :-

Please notice that I have clicked the third tab in the top element, and the first one in the lower

tab control itself.

=================================================================================================================

The first thing to notice with this is that although we have XAML script declarations of the Tab elements, the

tab items themselves are missing and therefore must be in code behind.

Study the details in the following image to check this out :-

=====================================================================================================================

The next small section is part of the SDK example, but it may not be that useful - however, it does

demonstrate how we can link up the click of a tab in the second element, and change both top and bottom

controls to show the same tab ... index values the same.

Here is the code - use it as you will ;-)

=============================================================================================================

Moving on :

Okay, we can now move on to try and add the tab items within the XAML script itself.

I have no idea why the Microsoft sample codes the items as most usually everything is placed in XAML script.

Anyway, below is shown me starting to enter via the XAML text editor :-

=============================================================================================

And when all the tab items for the first 'TabControl' element are done it looks like the following :-

================================================================================================================================

Yes! and it still works.

The code behind has been reduced to that shown below :-

========================================================================================================

However, the mark-up is so succinct that I will move the rest of the code into the XAML section.

And once the items are all in the XAML we have the benefit of seeing the element true nesting situation

in the DO pane - see below :-

==============================================================================================================================

Now we can adjust the size of the tab controls on the graphics surface to save space in these eNotes, as

well as building and running the app - see the results below :-

And a final look at the code behind shows we have little left after a bunch of comment lines :-

===========================================================================================================================

I suggest you try and make all these changes manually, using the XAML editor and the excellent Intellisense

which it has.

I quite enjoy using it I must say.

Events and Handlers :

Okay guys, so we think we have reduced the dotNet code behind to something small !? Well, we can also deal with the

selection of the event in script as well, Oh! and also set the value of the 'TabStripPlacement' attribute as well.

Let us first see what the code looks like after moving as much as possible to XAML script - study the following carefully :-

========================================================================================================

We will explain about the Boolean 'lReady' a little later, it is just to stop an error at start up.

The script changes will only occur on the second (or bottom) tab control element.

Below are a couple of images where I am using intellisense to add the attribute and its value for the TabStrip :-

===============================================================================================================

=================================================================================================

Then the next two images show me adding the script to choose the suitable event and its handler name :-

===================================================================================

=================================================================================================

Well, after all that editing of the script section we need to see what it looks like now - checkout below :-

==============================================================================================================================

Yes, you will also notice I could not resist having a little play with colours - the bottom tab element

has some changes to certain attributes - see if you can spot them !?

And here is a build and run :-

Why the Boolean at the Start ? :

If we leave the script and code as seen above, then when the InitializeComponent() method is run the event

will fire and at the point it does the selected index value is not determined. This would cause and error if we do

not handle it correctly, I know, I have just spent 10 minutes sorting it out ;-)

By adding code this way we choose a simple approach to stop the handler try to select a tab on the first TabControl

element.

If really, in one of my own apps, I would not switch the event handlers on (make the associations) till the Initialization

is complete. Anyone following my eNotes knows I like my 'Set' and 'Unset' event handler methods.

For now, appreciate that this is a learning exercise and we do some things for shortness and brevity ;O))

Going Further - Adding Elements to a TabItem :

So far the Microsoft sample has only had the contents of the separate tab items set as strings. Now we need to do

something much more realistic, and add others of different and various types.

Since the 'TabItem' element is a 'Content Control' it can have only one 'things' contained within it. So let us try with our

top tab control to make its first item contain a 'DatePicker' instead of a string value.

In the image shown below see how the script has been altered :-

==============================================================================

So when we build and run we expect that the text message on item one in the top tab control will have gone, and a

'DatePicker' to be in its place in some form or another - checkout below :-

Using the Second 'TabItem' :

If we now move on to use the second tab item of the top control, we can give it a content of a StackPanel, to which

we can then add multiple elements.

In the image below the script shows I have added three elements, a 'DatePicker', a 'TimePicker', and also a 'Button'.

Checkout carefully the following details :-

======================================================================================================================================

And this builds and runs to give the following :-

Although this looks good, be careful about the calendar dropping where it can be seen, I initially got the calendar to

pop upwards and much of it was not available for viewing.

So I have added the following - see highlighted section :-

===============================================================================

And as long as the Browser has enough available 'space' below the tab control we get the following functionality

which is acceptable, and works :-

After a couple of selections and text editing to the 'TimePicker' input, we see this below :-

====================================================================

To be quite honest, I think we have exhausted this sample for what it was designed to do and also teach us.

Let us move on to learn some other aspects of XAML and Silverlight.

See you in the next section .....

PHH - 2nd. February 2011.

Addendum :

We shouldn't miss the opportunity to see how to change our code, script, and settings such that an element

from the Toolkit (like TimePicker) can be correctly accessed for our apps.

Below is an image which shows the extra Reference needed :-

==========================================================================================

The above image also shows the nested structure of the final state of our Tab sample.

We now also need to include a suitable namespace reference in the script section - see below :-

===============================================================================================================

These additions will be required when we wish to use any of the Toolkit controls.

Now let us move on this time ...........


working script and code

===========================================================================

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;

namespace TabControls

{

public partial class MainPage : UserControl

{

private Boolean lReady;

public MainPage()

{

lReady = false;

InitializeComponent();

tab1.SelectedIndex = 0;

tab2.SelectedIndex = 0;

lReady = true;

//----- now all in XAML script section -----

}

//----- This handler responds to the user changing the selected

//----- TabItem on tab2 by changing the selection on tab1 to

//----- match.

void tab2_SelectionChanged(object sender, SelectionChangedEventArgs e)

{

//----- Set the selected TabItem of tab1 to match tab2 -----

if (lReady)

tab1.SelectedIndex = tab2.SelectedIndex;

}

}

}

===========================================================================

<!-- NOTE:

By convention, the sdk prefix indicates a URI-based XAML namespace declaration

for Silverlight SDK client libraries. This namespace declaration is valid for

Silverlight 4 only. In Silverlight 3, you must use individual XAML namespace

declarations for each CLR assembly and namespace combination outside the scope

of the default Silverlight XAML namespace. For more information, see the help

topic "Prefixes and Mappings for Silverlight Libraries".

-->

<UserControl

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

x:Class="TabControls.MainPage"

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

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

FontFamily="Trebuchet MS" FontSize="11" mc:Ignorable="d"

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

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

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

<Canvas x:Name="LayoutRoot" Background="AliceBlue" >

<!-- Create a simple TabControl in XAML. -->

<sdk:TabControl x:Name="tab1" Canvas.Top="63" Canvas.Left="48"

Height="100" Width="300" Margin="2,-51,-2,81">

<sdk:TabItem Header="First TabItem!" Content="This is the first TabItem's content."/>

<sdk:TabItem Header="Second TabItem !!" Content="This is the second TabItem's content."/>

<sdk:TabItem Header="Third TabItem !!!" Content="This is the third TabItem's content."/>

</sdk:TabControl>

<sdk:TabControl x:Name="tab2" Canvas.Top="0" Canvas.Left="0"

Height="130" Width="300"

TabStripPlacement="Bottom" BorderThickness="3" BorderBrush="Maroon"

SelectionChanged="tab2_SelectionChanged" Margin="50,158,50,12">

<sdk:TabItem Header="1st. TabItem!" Foreground="Maroon"

Content="This is the 1st. TabItem of the second TabControl."/>

<sdk:TabItem Header="2nd. TabItem !!"

Content="This is the 2nd. TabItem of the second TabControl."/>

<sdk:TabItem Header="3rd. TabItem !!!"

Content="This is the 3rd. TabItem of the second TabControl."/>

</sdk:TabControl>

</Canvas>

</UserControl>

===========================================================================

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

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

x:Class="TabControls.App"

>

<Application.Resources>

</Application.Resources>

</Application>

===========================================================================

<!-- NOTE:

By convention, the sdk prefix indicates a URI-based XAML namespace declaration

for Silverlight SDK client libraries. This namespace declaration is valid for

Silverlight 4 only. In Silverlight 3, you must use individual XAML namespace

declarations for each CLR assembly and namespace combination outside the scope

of the default Silverlight XAML namespace. For more information, see the help

topic "Prefixes and Mappings for Silverlight Libraries".

-->

<UserControl

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

x:Class="TabControls.MainPage"

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

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

FontFamily="Trebuchet MS" FontSize="11" mc:Ignorable="d"

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

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

d:DesignHeight="300" d:DesignWidth="400"

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

<Canvas x:Name="LayoutRoot" Background="BlanchedAlmond" >

<!-- Create a simple TabControl in XAML. -->

<sdk:TabControl x:Name="tab1" Canvas.Top="63" Canvas.Left="48"

Height="108" Width="300" Margin="2,-51,-2,81">

<sdk:TabItem Header="First TabItem!">

<sdk:DatePicker/>

</sdk:TabItem>

<sdk:TabItem Header="Second TabItem !!">

<StackPanel FlowDirection="LeftToRight" Background="Cornsilk">

<sdk:DatePicker Width="262" IsDropDownOpen="True"/>

<toolkit:TimePicker Width="183"></toolkit:TimePicker>

<Button Width="190"

Foreground="Red">I am the Third element in contents!</Button>

</StackPanel>

</sdk:TabItem>

<sdk:TabItem Header="Third TabItem !!!" Content="This is the third TabItem's content."/>

</sdk:TabControl>

<sdk:TabControl x:Name="tab2" Canvas.Top="0" Canvas.Left="0"

Height="130" Width="300"

TabStripPlacement="Bottom" BorderThickness="3" BorderBrush="Maroon"

SelectionChanged="tab2_SelectionChanged" Margin="50,158,50,12">

<sdk:TabItem Header="1st. TabItem!" Foreground="Maroon"

Content="This is the 1st. TabItem of the second TabControl."/>

<sdk:TabItem Header="2nd. TabItem !!"

Content="This is the 2nd. TabItem of the second TabControl."/>

<sdk:TabItem Header="3rd. TabItem !!!"

Content="This is the 3rd. TabItem of the second TabControl."/>

</sdk:TabControl>

</Canvas>

</UserControl>

===========================================================================

===========================================================================

===========================================================================

PHH - 3rd. February 2011.


ScrollViewer

====================================================================================================

===============================================================================================================

PHH - 31st. January 2011.


Our own example

Hi you guys, we are going to have fun with the 'ScrollViewer' control, and learn how to make it do

some useful things for us.

Then in later projects we can use it in many places, like 'TabControls' for example.

I did not use it in the last section on 'TabControl' elements since we had enough to focus upon.

Close all projects and solutions which may be open in your VS10 shell.

Use File ... New ... Project ... to create and open a new project named "ScrollViewer" - see below :-

==============================================

The editor area of our design surface looks like this :-

=================================================================================================================

Now open the "All Silverlight Controls" folder (or tab) in the Toolbox pane, and from the list drag

as shown below :-

===========================================

Then drop the object onto the graphical part of the design surface as shown in the following image :-

===============================================================================================================

The first thing we need to do in the XAML text editor is to add a full end tag to the 'ScrollViewer' section.

Highlight the last characters in this section, that is ' /> ' and then press ' > ' and enter, this brings up the

following script :-

==================================================================================

Okay then, let us make a simple start and try and place a small snippet of Shakespeare into a TextBlock

element and use this object as the content for the ScrollViewer.

For the settings and values of the associated attributes for ScrollViewer and TextBlock I am taking as a guide those

shown in the earlier MS 'Sample Browser' example.

Here is what we get at build and run time :-

And here is the XAML script which generates this - checkout the following :-

==================================================================================================================

Please note that in the script section we MUST make sure that the automatic tabbing and spacing

between lines does not insert into our sample text anything at all - we supply the carriage returns (or enter)

characters.

To be perfectly honest with you, at this moment in time I am not sure what the relationship is between what

size we set the TextBlock, and what size we set the ScrollViewer.

At least it works, and is not silly in any way. So that is a start for us in this very uncertain world of change !!

We certainly need to do some more exploring and experimenting - which is what I like doing ;0))

Possible Answers / Causes :

Oh! I see, I have just looked at the sample script from the Sample Browser app and there are no carriage

returns / enters in it at all.

I think the easiest thing for us to do is make a text file and then open and use that. Lets give it a go and see.

BUT - first - let us make the text a single line in the XAML editor and try again, after making a few minor

adjustments to the width of the TB and height of the SV.

=============================================================================================

Checkout below the results :-

Notice that one benefit of using the Browser is that we can enlarge the content - note this has

been increased to 125%.

Oh! and the whole point of doing the experiment was that the look/feel of the SV now feels as

it should to my mind.

Now to use a file.

External text file use : [ Security, and Restrictions ]

Well, what we wish to do now, allow quite simple and somewhat 'routine', it open up a BIG issue with which

we must get to grips, as we will sometimes be hoping to access files on other user's PC platforms.

This includes saving data as well as reading it.

Before we can start to run experiments with our script and code changes we need to place a simple text file

in a couple of folders on the PC.

Checkout below the two folders :-

=====================================================================================================================================================

And now the root folder of my user documents on this PC - as I have logged in :-

And finally see the file contents just for good measure :-

If I now try to run the app as it was developed, running through the browser I get the following :-

As we will see I have trapped the level of permissions and if this is not done we get an error.

See below for what happens :-

Explaining what is going on :

We need to go through the next section slowly, and understand each part as wee go.

The next image below shows how the app may be got to work as we seem to require, BUT, notice

one big difference - try to spot it for yourself :-

Yes, you may have noticed that the app is running in a Window and not a Browser !

Also, from the following image we can see we have an extra entry in the SE pane, under 'Properties'

see below :-

=============================================

How to handle the 'OutOfBrowser' (OOB) settings :

Believe it or not, once I had found the right information in a help text book, it was easy to get some success

when the app is built and run.

There are two big issues - one is where we place the file to be opened and read - the other is how we set

the app to run in a Window in place of the Browser.

Running through the Browser seems to be VERY restrictive as far as file access is concerned, but running

"Out Of the Browser", in a Window allows some file access but not to any folder on the disk drives available.

Setting the OOB details :

In the SE pane right click the Project item (here it is called 'ScrollViewer') and from the context menu choose

the Properties item.

This opens a new tab in the central work area like seem in the image below :-

===============================================================================================================================

Notice we need to have the 'Silverlight' tab in use at the left hand side of the screen.

Now if we check the control entitled 'Enable running application out of the browser' we get this :-

====================================================================

And this opens a further dialog screen into which we can make a few simple entries about the Window

which will be used in place of the Browser. What it opening dimensions will be and where is is to be place

on the display (monitor) when it is opened initially.

Study the details shown in the image below :-

And finally below we see the new window with its top left corner at position 100, 100 and the Window

itself 500 units square :-

===============================================================================

And for some fun during this difficult stuff here it is at launch time when the size is set at 130 by 130 :-

Either way the app is running without error and is also reading the text file - and as long as the text file is

NOT placed in "certain" folders that will always be the case.

Before we move on to look at the folder restrictions, let us look at what the design system has created in the OOB

' .xml ' file. Obviously this acts as data when the app is instantiated and run etc..

Check this out :-

=====================================================================================================================================================================================================================

It is easy to see that the Window dimensions and placement values are encapsulated in the XAML script.

We will deal with Permissions in another section.

Note the task bar and how it looks when an OOB app is running :-

What are the OK folders, and what does our code look like ? :

Let us first of all look at the C# code which is working right now.

Please realise that there is a purpose to leaving 'commented' the different 'filepath' string lines of code. We both know

what we have tried previously, and also can try again later :--

==================================================================================================================

The method 'ReadFileDirect' is basically the same as the event handler method, it just means we can run it

when the app starts, and don't have to respond to a user's click.

First thing to notice is that when the app first loads the content of the 'ScrollViewer' is just one line - see below :-

=========================================================================

After clicking the button we get the file read and the content refreshed with many more lines - see below :-

============================================================================================================

Obviously on the way to reading and displaying we got this :-

There are a few other folders and sub-folders which work - BUT - what if we change the 'OOB' mode ?

By simply un-checking the control in the properties dialog screen for 'OOB' we get the following :-

So unless we re-check the option get get back our OOB mode we will not even be able to test out the

different folder choices - to see which will work.

The difficult bit - Proof !? :

It is now a bit tricky to show in notes what appears to be happening at this end, when testing out different folders.

Here is an image to show I have the correct file in the right folder :-

=======================================================================================================================================================

Yes, we seem to have a copy of our Shakespeare text file in the Temp directory in the root of D: drive.

But when we run our app using this filepath we get this :-

===================================================================================================================================

If I try now try a few more we get the same sort of failure for all folders except those in the User area

I am currently logged into.

I am logged in as 'BEST' and so trying a new directory in my own user area I first get this :-

And then this shown below :-

=================================================================================================================================

And finally, going back to the first user area folder I tried (before I knew about 'OOB') this is what

we now see :-

================================================================================================================

In fact the eagle eyed amongst you will have noticed that I have clicked the push button a second time,

in order to get the the message box over the top of an already filled 'ScrollViewer' ;-)

Well spotted, all those that did !

With my newly found knowledge about OOB I will move on to do some work in the Dialog Boxes section (Chapter 9).

I may well see you next in the ProgressBar section however.

See you there ...........

PHH - 3rd. February 2011.


working script and code

=============================================================================

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;

//-------------------------------------

using System.IO;

namespace ScrollViewer

{

  public partial class MainPage : UserControl

   {

      private string fileLoc;

      public MainPage()

       {

           InitializeComponent();

          //this.ReadFileDirect();

       }

      private void myReadFile(object sender, RoutedEventArgs e)

       {

          if (Application.Current.HasElevatedPermissions)

           {

              //----- direct filepath << alternative to Environment >> -----

              //this.fileLoc = "C:\\Users\\BEST\\Documents\\Visual Studio 2010\\Projects\\"+

              //    "ScrollViewer\\ScrollViewer\\Bin\\Debug\\Shakespeare.txt";

              this.fileLoc = System.IO.Path.Combine(Environment.GetFolderPath(

              Environment.SpecialFolder.MyDocuments), "Shakespeare.txt");

              //this.fileLoc = "D:\\Temp\\Shakespeare.txt";

              //this.fileLoc = "C:\\Users\\BEST\\Documents\\Temp\\Shakespeare.txt";

              MessageBox.Show(fileLoc, "File Detail :", MessageBoxButton.OK);

              if  (File.Exists(fileLoc))

               {

                  //----- Display the contents in a TextBox -----

                  using (StreamReader sr = new StreamReader(fileLoc))

                   {

                       myTB.Text = sr.ReadToEnd();

                       myTB.Visibility = Visibility.Visible;

                   }

               }

              else MessageBox.Show(fileLoc, "Can't find file !? ...", MessageBoxButton.OK);

           }

          else MessageBox.Show("Not got permissions !? ...", "PERMISSION ? :", MessageBoxButton.OK);

       }

      private void ReadFileDirect()

       {

          if (Application.Current.HasElevatedPermissions)

           {

              //----- direct filepath < alternative to Environment > -----

              //this.fileLoc = "C:\\Users\\BEST\\Documents\\Visual Studio 2010\\Projects\\"+

              //    "ScrollViewer\\ScrollViewer\\Bin\\Debug\\Shakespeare.txt";

              //this.fileLoc = "C:\\Program Files (x86)\\Shakespeare.txt";

              //this.fileLoc = "C:\\Temp\\Shakespeare.txt";

              //this.fileLoc = "C:\\Shakespeare.txt";

              //this.fileLoc = "D:\\Temp\\Shakespeare.txt";

              this.fileLoc = "C:\\Users\\BEST\\Documents\\Temp\\Shakespeare.txt";

              //this.fileLoc = System.IO.Path.Combine(Environment.GetFolderPath(

              //Environment.SpecialFolder.MyDocuments), "Shakespeare.txt");

              MessageBox.Show(fileLoc, "File Detail :", MessageBoxButton.OK);

              if  (File.Exists(fileLoc))

               {

                  //----- Display the contents in a TextBox -----

                  using (StreamReader sr = new StreamReader(fileLoc))

                   {

                       myTB.Text = sr.ReadToEnd();

                       myTB.Visibility = Visibility.Visible;

                   }

               }

              else

                  MessageBox.Show(fileLoc, "Can't find file !? ...", MessageBoxButton.OK);

           }

          else

              MessageBox.Show("Not got permissions !? ...", "PERMISSION ? :", MessageBoxButton.OK);

       }

   }

}

=============================================================================

<UserControl x:Class="ScrollViewer.MainPage"

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

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

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

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

  mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="400">

  <Grid x:Name="LayoutRoot" Background="White">

      <ScrollViewer Height="200"

                    Name="scrollViewer1"

                    Width="220"

                    HorizontalScrollBarVisibility="Visible"

                    VerticalScrollBarVisibility="Visible">

          <TextBlock TextWrapping="Wrap" Width="325" Name="myTB"

                    Text="Now is the winter of discontent made glorious summer by this death of York!">

          </TextBlock>

      </ScrollViewer>

      <Button Content="Read File" Click="myReadFile" ClickMode="Press"

              Name="pbReadFile" Margin="12,12,0,0" Height="23"

              VerticalAlignment="Top" HorizontalAlignment="Left"

              Width="89" />

  </Grid>

</UserControl>

=============================================================================

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

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

          x:Class="ScrollViewer.App"

          >

  <Application.Resources>

  </Application.Resources>

</Application>

=============================================================================

<OutOfBrowserSettings ShortName="ScrollViewer Application" EnableGPUAcceleration="False" ShowInstallMenuItem="True">

 <OutOfBrowserSettings.Blurb>ScrollViewer Application on your desktop; at home, at work or on the go.</OutOfBrowserSettings.Blurb>

 <OutOfBrowserSettings.WindowSettings>

   <WindowSettings Title="ScrollViewer Application" Height="400" Width="400" Top="100" Left="100" WindowStartupLocation="Manual" />

 </OutOfBrowserSettings.WindowSettings>

 <OutOfBrowserSettings.SecuritySettings>

   <SecuritySettings ElevatedPermissions="Required" />

 </OutOfBrowserSettings.SecuritySettings>

 <OutOfBrowserSettings.Icons />

</OutOfBrowserSettings>

=============================================================================

PHH - 5th. February 2011.


ProgressBar

==================================================================================

===============================================================================================================================================

PHH - 31st. January 2011.


Our own example

PHH - 3rd. February 2011.


RepeatButton

Let us see what the SDk sample browser has to offer us first, before we branch

out and do our own thing ;-)

=====================================================

=============================================================================================

==============================================================================

PHH - 31st. January 2011.


DatePicker

PHH - 1st February 2011.


TimePicker

This control is in the Silverlight Toolkit and so the details will not be found in the standard CHM file

for Silverlight 4.

So we need to look in the CHM file for the Toolkit - see below for a glimpse at both :-

==================================================================================================================================================================================

PHH - 1st February 2011.


Chapter 9 - Dialog Boxes

Let us take a look at the SDK documentation :-

Common Dialog Boxes :

Silverlight offers three commonly used modal dialog boxes: a dialog box to open files, save files, and specify print settings.

Security Restrictions for Common Dialog Boxes :

For security purposes, if a Silverlight application is a sandboxed application, file and print dialog boxes must be user-initiated.

This means you must show them from a user-initiated action, such as the click event handler for a button.

If you attempt to show a dialog box from non-user initiated code, a SecurityException will occur. In addition, there is a limit

on the time allowed between when the user initiates the dialog and when the dialog is shown.

If the time limit between these actions is exceeded, an exception will occur.

When you are using the Visual Studio debugger with a dialog box, a SecurityException will be thrown if you set a breakpoint

between dialog box creation and showing the dialog box.

Because of the user-initiated restrictions, this is the expected behavior.

If you set a breakpoint after the call to ShowDialog, no exception will be thrown.

More on Security - and its Restrictions :

If you attempt to show the dialog box from KeyDown event handlers and other synchronous calls to application code, such as

LayoutUpdated or SizeChanged event handlers, an exception will be thrown.

However, an exception will not be thrown when the application is hosted in Internet Explorer, running in protected mode.

The Silverlight plug-in has limited support for dialog boxes when the plug-in is in full-screen mode.

In most cases, displaying the dialog box in full-screen mode will cause the plug-in to revert to embedded mode.

However, to avoid issues on some browsers, you should exit full-screen mode before using these classes.

In Silverlight applications that run outside the browser, you can display a prompt to the user to enable dialog boxes in full-screen mode.

Also, the user initiation restrictions are relaxed for trusted applications. For more information, see Trusted Applications.

PHH - 4th. February 2011.


OpenFile

In Visual Studio close down all solutions and projects currently open.

Start a new Project/Solution called 'DialogBoxes' - using the Silverlight template in C#.

Then right click the solution item in the SE pane and start a second new project.

Call the second one 'DialogOpen' and set this via the context menu to be the startup project.

From the toolbox drag a push button and a TextBox onto the graphical design surface and then

add a little colour, and a single event to the Button.

Study the following image and make your script and code this that illustrated below :-

========================================================================================================================

[ .. note the DO pane refreshed after this and now looks as shown below :- .. ]

====================================================================

Here are a few snips of me using intellisense to add the event :-

=====================================================================================================

======================================================================================

And the stud method handler created in code is like this :-

=========================================================================================

Okay guys, lets build and run, and this is what we see :-

The Dialog Box itself :

If we add a few lines of code to our handler we then get something a lot more interesting - see below :-

============================================================================================================

It looks to me as if this is all going too well, it too easy, and as yet no error messages !!

Let us now add some code and enlarge the graphical area of the TextBox. then we can see if we

are allowed to open and read the selected file.

Study the code below :-

==========================================================================================

And now the results of a build and run, and button click and file select are shown above the adapted script :-

======================================================================================================================

Trying out Other Folders :

I will now show you the visual results of testing by trying to open a text file from a number of

folders which previously proved 'difficult' in the ScrollViewer section.

It would appear that when going through the FileOpenDiag on my PC with access setting as they are,

I can navigate to and open and display, the .TXT file when it is placed in any folder - even the Programs folder of C:\ drive.

Study this image below :-

=============================================================================================================

This has all been done without the need to resort to the OOB ('Out Of Browser') approach.

However, it is a good idea to test out the the OOB so here goes :-

==============================================================================================================================

Notice that I did not set the check option in the OOB Settings dialog, for 'requiring elevated trust etc. and

yet it still opened the file in the Program folder.

So we are getting a feel for these folder restrictions, and it would seem to me that Windows 7 does some

sensible things when the user is selecting using DialogBoxes.

Before we close this section, here is a totally unrelated '.txt ' file found in the root of C: drive, opened and displayed :-

Let us move on to see what we can achieve with the 'Save' and 'Print' variety ;0)

See you in the next section .....

PHH - 4th. February 2011.

Addendum :

The tidied and fuller working app for the website (ClickStartVulcan2.net) is as shown below :-

The script and code in the 'working' subsection is for the app in this state.


working script and code

===================================================================================

<UserControl x:Class="DialogOpen.MainPage"

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

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

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

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

mc:Ignorable="d"

d:DesignHeight="214" d:DesignWidth="332">

<Border BorderThickness="3" BorderBrush="Violet" Height="210" Width="320">

<Grid x:Name="LayoutRoot" Background="AliceBlue" Height="195" Width="309">

<Button Content="Find and Read File"

Height="23" Width="137"

HorizontalAlignment="Left"

Margin="13,15,0,0" Name="button1" VerticalAlignment="Top"

Click="button1_Click" ClickMode="Press">

<ToolTipService.ToolTip>

<ToolTip Content=" .. press to bring up 'Open File Dialog' .."

HorizontalOffset="10"

VerticalOffset="20"/>

</ToolTipService.ToolTip>

</Button>

<TextBox Height="131" HorizontalAlignment="Left"

Margin="13,51,0,0" Name="textBox1" VerticalAlignment="Top"

Width="285" Background="BlanchedAlmond" TextWrapping="Wrap">

<ToolTipService.ToolTip>

<ToolTip Content="File content of .TXT and .XML files will be displayed here."

HorizontalOffset="10"

VerticalOffset="20"/>

</ToolTipService.ToolTip>

</TextBox>

<Button Content="Clear Text" Height="23" HorizontalAlignment="Left"

Margin="223,15,0,0" Name="pbClearText"

VerticalAlignment="Top" Width="75"

Click="myClearClick" ClickMode="Press">

<ToolTipService.ToolTip>

<ToolTip Content="Use me to clear the display area."

HorizontalOffset="10"

VerticalOffset="20"/>

</ToolTipService.ToolTip>

</Button>

</Grid>

</Border>

</UserControl>

===================================================================================

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;

//---------------------------------------

using System.IO;

namespace DialogOpen

{

public partial class MainPage : UserControl

{

public MainPage()

{

InitializeComponent();

}

private void myClearClick(object sender, RoutedEventArgs e)

{

textBox1.Text = "... ready for file read ...";

}

private void button1_Click(object sender, RoutedEventArgs e)

{

OpenFileDialog OFD = new OpenFileDialog();

OFD.Filter = "Text files (*.txt, *.xml)|*.txt;*.xml";

bool? userAccepts = OFD.ShowDialog();

if (userAccepts == true)

{

//----- open the accepted file to read -----

Stream fs = OFD.File.OpenRead();

using (StreamReader sr = new StreamReader(fs))

{

textBox1.Text = sr.ReadToEnd();

}

fs.Close();

}

}

}

}

===================================================================================

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

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

x:Class="DialogOpen.App"

>

<Application.Resources>

</Application.Resources>

</Application>

===================================================================================

===================================================================================

PHH - 6th. February 2011.


SaveFile

PHH - 4th. February 2011.


Print

PHH - 4th. February 2011.


Custom

PHH - 4th. February 2011.


Chapter 10 - User Control

=================================================================================

======================================================================================

======================================================================================

PHH - 31st. January 2011.


Chapter 11 - RichTextBox

RichTextBox (RTB) :

This GUI element, or control, is a very useful one which has a wide range of possible uses.

We need to get to know and thoroughly understand what the RTB control is, and what it has to offer.

Like all thing WPF is is completely founded on 'objects' and as such is quite different in MANY ways to that

other control in WinForms which had a similar name.

Let us see what the SDK documentation has to say, as a start to our own exploring :-

RichTextBox is a control that enables you to display or edit rich content including paragraphs, hyperlinks,

and inline images.

TextBlock, TextBox, or RichTextBox :

Silverlight includes three core text controls: TextBlock, TextBox, and RichTextBox.

The text control that you use depends on the scenario.

The following table lists some scenarios and the recommended control.

==========================================================================================================================

As I read this it seems to suggest that 'TextBox' and 'TextBlock' deal with strings of characters - no formatting.

And that 'TextBlock' is not for change or editing.

RTB on the other hand deals with display and editing of 'rich' text - which is far more complex than 'strings' alone!

Here is some helpful information on the 'Content Model' of the RTB.

Content Model :

RichTextBox supports a block-based content model.

The content property of RichTextBox is Blocks, which is a collection of Paragraph elements.

The Paragraph element can contain elements that are derived from 'Inline'.

The following illustration summarizes the content model for RichTextBox and shows how elements derived from

'Block' and 'Inline' fit into this model.

RichTextBox Content Model Diagram :

==========================================================================================================================

The SDK documentation goes on to say the following - some of which is NOT immediately useful it would seem.

Study this carefully :-

==========================================================================================================================

Our First Example :

Close all solutions and projects in VS10.

Create a new solution / project called 'RichTextBox'.

Base the new project on the C# template for Silverlight, and make it local.

Immediately create a new project called RTB1 and set this at the startup project.

If you do this you should end up with something similar to that shown below :-

=======================================================================================================================================

Okay you guys, we have a start, so now let us add some useful detail to our script.

Adding some XAML script :

This time I have added the new control by inserting text into the XAML editor, rather than using the

'drag / drop' facility from the Toolbox.

Quite often it is helpful to 'copy and paste' sample script from SDK docs and other examples, directly into

the XAML editor as suggested above. Then a few adjustments can easily be made once the bulk of the

script is in place.

Here is what we now have - type it into your own VS shell :-

===================================================================================================

Notice a few things - like I have chosen to run as OOB, so the images in these eNotes are cleaner.

Checkout Chapter 9 if you are unfamiliar with OOB (Out Of Browser) mode of running.

Also notice in the above image that we have a running app shown which has been resized to something

quite small, and the 'rich text' has wrapped itself onto the second line.

A third thing to notice is that when the RTB is in focus (in this simple case this means the app Window) then

the colour of the Border is not shown as red.

The following two images show this Border behaviour as well as the resizing of the controls to

long and thin :-

Okay I here you say, "Let's have a silly 'squash' to see what happens" - well here we have it :-

This shows the 'Auto' setting of the vertical scrollbar in action.

And below we action the scrollbar itself to see the bottom of the contents of the element :-

How to Code the 'RichText' :

At this point, before we launch off to do more exciting things, we ought to see how we produce some Rich Text

using dotNet code.

First of all I have commented that small amount of text we were using - see below :-

==============================================================================================

And then we have added a section into the dotNet code behind, as see in the following image :-

======================================================================================================

In the image shown above we have added the lines 38 through 41 to those included in the SDK.

We have added font weight and size properties to an 'Italic' object type. Note that you can do similar stuff

to the Run and Bold types, and below you see me adding some colour to a run object :-

==========================================================================================

Context Menu :

Before we move on to learn some more new stuff about Rich Text Boxes, let us try out the right mouse

click to see what Context Menu options are currently available - checkout below :-

As you can see, not a lot on offer :(

However, we can try to drag an item from the extended Toolbox, in which we have the Toolkit entries, as well as

those for the standard "AllSilverlightControls".

Here is what I can see :-

=========================================

Going so far and no more ! :

In this section, where we are really focused on the functionality of the RTB control, we will try to put in place a small

and working Context Menu (CM), but then leave the full extent of the work on CM to the relevant section under Chapter 4.

Here is what I have working after just a small amount of editing :-

===========================================================================

And the script which was put in place to give this extra functionality is as follows :-

=======================================================================================================

For this live testing phase we have placed three menu items within the 'ContextMenu' itself.

In the script shown above look out the even on the RTB entitled 'MouseRightButtonDown' - in the fourth line.

The dotNet method handler for this is shown below - the code which displays (and hides) the menu along

with it's items.

Study the details carefully :-

============================================================================================================================

I am sure there may be better ways to do this, but for now it at least does the job at displaying the menu

ready for selection.

Finally on Context Menu :

And a final few changes related to the ContextMenu, before we return to the rest of the serious stuff on the RTB

itself.

Take a look at the output at build and runtime :-

=========================================================================

And now the current script to do this :-

========================================================================================================

And now the accompanying code behind :-

==========================================================================================================================

Moving on :

I think we have done enough by way of an introduction to the RTB control, and now we to finish here

and move to a special subsection or two where we look at issues like editing, formatting, saving to file, and

loading from file.

Lots to look into and explore.

See you in the next section ................

PHH - 6th. February 2011.


What is Rich Text ?

PHH - 12th. March 2011.


Saving the RichText to disk

Before we can save any information to a file on disk we need to have an easy way to get 'hold' of

what we currently have in our RTB control.

The RTB element has a property entitled 'Xaml' which helps us do just what we require.

The SDK documentation says this about the attribute :-

Gets or sets a XAML representation of the content in the 'RichTextBox'.

Property value - a String object that is a XAML representation of the content in the RichTextBox.

=======================================================================================================

After reading this information I do not think it will take much effort to be able to read the full object content of

the RTB and hold into as a string - which we can the redisplay or save to disk.

Have a look at the following image which shows a message box displaying the information retrieved using the

'.Xaml' property :-

You will notice that I used for convenience an extra entry in the context menu - sorry there ought to have been

a space between the 'Display' and the 'Details' - I will add this now.

If we look at the code behind which makes this happen we see the following :-

=============================================================================================================

So we need to change our original demo app to explore this topic further. It is probably better to make a new project,

one called RTB2.

Let us do this now.

And before we look in any detail at the script in front, and the code behind, here is the result at run time :-

Obviously we start with and empty 'TextBox' before we click the button to 'copy' - see below :-

Let us start by looking at the script in front - see below :-

======================================================================================================

Notice that the contents of the RTB element are all done in the dotNet code - there is nothing specified in

the XAML script.

Since only the dotNet event handler is new, we will look at that below :-

=================================================================================

Well, you can't get much simpler than that ;-)

So what we need to do next is save this 'string' to disk file using a Stream writer and the 'SaveFileDialog' element.

Saving Text String to File on Disk :

Once again I have searched the SDK documentation for some help and guidance, and have found some useful

dotNet code to open a suitable Dialog screen and save some test string data to file.

Here is what I have copied over into our working app :-

======================================================================================================

So, as you can see in the above image, we are hoping to get a small text file ( '.txt' ) with the test contents

shown in line 80.

Obviously, the handler method is designed to work with a new button which has been added to our SL form.

Here is the new button -script :-

=====================================================================================================

So building and running our updated app does the following :-

[ ** notice ** that I am using what should be a safe folder destination within my user documents area ... ]

And after the Dialog closed I used WE (Windows Explorer) to see the following :-

The new file appears in the WE list, and I have also opened this in Notepad for us to see the contents.

Saving our real RT contents :

Okay then, all we now need to do is substitute the test string with our real string object. Then we will get a file

which contains our RTB information.

First let us see the altered code behind :-

======================================================================================================

And when we run this we get the following :-

Saving this filename then closes the Dialog and we are returned to the SL app 'MainPage'.

Using WE we see this below :-

So viewing the above images it would appear that we have been successful and that our Rich Text has

now been placed into a file.

Let us move on to the next section when we see how to read back this file content so that it may be

displayed within a RTB on our form.

See you in the next section ................

PHH - 7th. February 2011.


Reading in RichText from disk

PHH - 7th. February 2011.


Screen Formatting

PHH - 7th. February 2011.


Adding Images to the text

PHH - 7th. February 2011.


Chapter 12 - Images and Icons

The way we create sources for Image UI elements is different in Silverlight to the way we have seen it done

previously in WPF.

It is the way' BitmapImages' are instantiated that can cause developers some grief. It is not the sort of

place, or area, where we expect to see a difference.

Study the following lines from a working SL5 application :-

=========================================================================================================

PHH - 7th. February 2011.


Chapter 13 - Making Tool Ribbons and Bars

Study the following image :-

========================================================================================================================

Whatever you wish to call the area at the top of the above application, it does the same job as

the old fashioned menu bar and drop / fly-out menus.

This then became the Toolbar and its icons, and now some like to use the term 'Ribbon' for the latest

of these 'quick access' graphical 'facilitators'.

Yep! I suppose I am saying that they are all the same - which in a way they are.

So we will look at what we can do for Silverlight apps, using some standard and basic tools. yes, I know, your friend

has a free download which does Ribbons and Bars etc. - BUT - we need to learn some skills in SL so we will start

by first of all trying to make our own.

Then we can always look at third party stuff - to make our life easier from then on.

Before moving on we may as well see the context menu as well - this will also give us some ideas for our SL work.

Here is a live sample I have in front of me :-

=========================================================

Using the right mouse click within the editor does not bring up that annoying Silverlight option. But right

clicking elsewhere in the Editor app does bring up this shown below :-

======================================================

Yes, quite annoying this 'Silverlight' default menu !

Getting Rid of the Built-in context menu :

Looking at the code behind for the sample MS Editor application, we see this for bringing up the context menu :-

============================================================================================

We need to experiment and explore the sample script to see what is done to override the default behaviour.

PHH - 7th. February 2011.


Chapter 14 - DataGrid element

The 'DataGrid' control is as always a VERY useful element for us to have in our Toolbox.

We could probably make a large section of eNotes just on this control alone, however, we need to make a simple start

as well as making sure we leave plenty of complexity to discuss another day ;-)

Below we will see the simplest, and easiest, way to display a DataGrid element which contains some custom data.

Checkout the following image and its supporting details :-

In our above image we have two elements, for the details of the TextBlock and DataGrid see the XAML script below :-

============================================================================================================

The XAML script, shown in the image above, has information which places and displays the TextBlock as well

as the DataGrid.

*** Note ***

The DataGird element is one of the 'Common' tools in the Silverlight 4 Toolbox - see below :-

======================================

What XAML script in front does not do is define any data items.

The image shown below is how our test app looks before we use the C# code behind to populate our

DataGrid rows :-

=====================================================================

When test app is built and run then our code behind provides the data values.

We need now to study the 'Customer' class which is what our code uses to create a list of data items which

is then provided as the 'ItemsSource' .

Study in detail the code shown below - first we see the 'Customer' class itself :-

=============================================================================================

And now we need to take a look at how we use the 'GetSample.....' static method in order to provide a list

which can be supplied as the source of data to the DataGrid element - see the following code section :-

===============================================================================================

As you will agree, this is quite straightforward.

To Summarize :

PHH - March 13th. 2011.


Going a little further

Before we look at any details, let us take a look at the screen output display at runtime :-

And to indicate what is actually under the direct control of the developer (us), we can produce the following

with only a few small changes :-

When we use the mouse to pint at an item line in the grid, and the click it, we get an extra line - below that selected -

which is basically made up of what we as the developer choose it to be !

Or if we use a little more of our knowledge we can do this as shown in the following image :-

Time to look at XAML script detail ! :

Since the script to do the most complex of these (the last image shown) is not that complex, we may as well

miss out the two earlier stages and examine the details of the image immediately above, here is the the script :-

=============================================================================================================================================

Notice line 18 of the XAML script which defines that the extra 'row detail' is only displayed for the selected row.

If the enumeration is changed to that shown below :-

==============================================================

then we get all rows displaying such information, as shown in the following image :-

Before we move on to the next section we need to remind ourselves that we have not ourselves controlled

which columns appear in the data grid, and what the headers are either.

Let us now move on to see just what may be done to take control over column display and the style and

form of the columns headers.

See you in the next section ............

PHH - 15th. March 2011.


and Further still

Once again, let us first look at the results of the new XAML script changes, before we examine

the details.

Study carefully the detail of the output display show below :-

Things to Notice :

The DataGrid is editable, and all columns may be changed.

The third row is currently having its Address field changed, and the foreground colour of the TexBox is

showing 'Blue'.

The header of the fourth column is 'clipped' and some detail is lost as the columns have not been resized

with the mouse.

All the columns have been defined by us in the XAML script, nothing has been done automatically.

The columns widths may be changed at runtime.

There is a word wrap feature set on the third field containing the address details.

There is a data field missing - that of Age. This is because I added this extra to the SDK sample, and until

I change the script we are still using the XAML in the Microsoft sample.

Finally, before the full scripting section - see what we can do to improve the fourth field / column, by using

a new syntax, that of the ' * '.

=============================================================================================================================================

Okay then guys, let us now see the full XAML script for the above version of our 'DataGrid' test app :-

=================================================================================================================================

Notice rows 34 & 35 - they were used when the 'New?' column header was clipped.

Let us add the extra column of mine, the one for Age - check this out :-

===================================================================================================================================

Note I have resized the windows somewhat and enlarged the Address header by dragging the right column divider with the mouse to the right.

The columns with 'window' relative formatting then re-adjust to what you see.

The following information from the SDK documentation may be helpful :-

=========================================================================================================================

I think you will see that we have used each of the possible values in our tests and trials.

Now to move on to the next section, see you there ................

PHH - 15th. March 2011.


Fuller Customisation

Once more, let us see the results on screen before we look at the detail of the XAML scripting.

Here are the results of the developer making customised adjustments to the definition of the DataGrid element.

Check this out :-

And after some more of my customisation her is the same thing with a couple more data records :-

Before we make any more 'improvements' let us checkout the script as it stands at the moment :-

==============================================================================================================================

Notice that - as with all custom defined columns - the text information of the column needs to be bound to one or more

of the properties in the data object - remember we have Customer objects in a 'typed' list.

The Address and Age columns are simple, in that we have one property bound to the field. However, the 'Name' column

is a composite column, and is made up from both first and last 'names'. As per usual we use a StackPanel to effectively

concatenate a couple of text boxes.

Also notice for this complex column, we specify a template for both the look of the cell, as well as what it should be when

in the process of being edited.

And if we need to make it obvious what we have defined for Name column editing, here is a better choice of colours :-

==========================================================================================

In the image below note lines 27 through 29 as they all have a new background colouration.

=====================================================================================================================

The text string 'Oil' is black simply because those characters have been highlighted with a mouse drag.

Enough of new things for a while, lets finish now, and have a break ;-)

See you in the next section ..........

PHH - 15th. March 2011.

Addendum :

The example we have built above, allows us to both resize the columns with the mouse, as well as to re-order

the columns themselves - see the following images :-

and this rearranged one too :-

De-Selecting row items :

Sometimes we wish to remove the selection from data rows. Below is an example of where we have selected

multiple rows, and then by using an extra button and its functionality, leave the DataGrid unselected, but with the

same cell in focus - that of 'Willie Wonker'.

===================================================================================================

======================================================================================

PHH - March 16th. 2011.


Changing and Saving grid data

No Changes at all ? :

If we use the property called 'IsReadOnly' we can set the grid so that all existing data can't be changed.

In my script lines below I have set it back to allow editing, after doing a demo test and trial etc..

====================================================================================================

The new 'DataForm' control :

If we search in the CHM file which came with the latest Toolkit for Silverlight 4, we see an extra UI element,

a control called the 'DataForm'.

Here is an example from a web search :-

===================================================================

=================================================================

PHH - 16th. March 2011.


Grouping, Sorting and Filtering

PHH - 16th. March 2011.


Chapter 15 - Data - Use of, Access to ...

PHH - 16th. March 2011.


Chapter 16 - Custom Data, Binding

Well, in this chapter we have 'come of age' !

By this I mean that we have now learned a lot from previous WPF, and XAML research and experiences, to be able

to construct a 'Custom' data class which use the full registration of properties with the Dependency Property system

running behind WPF and Silverlight.

Please realise that 'Binding' is only one of a possible four DP subdivisions as seen below :-

Dependency properties provide support for value expressions, data binding, animation, and property change notification.

[ *** Represents any property that is registered with the Silverlight dependency property system. *** ]

So of these :-

- value expressions

- data binding

- animation

- change notification

we will in this app be looking at 'Binding'.

I will use the term 'Binding' for both our our custom data class type of data, as well as the more general UI element binding

from one property to another, where the source can be custom and/or property value related.

It is my personal opinion that once a developer gets to use the 'Binding' system regularly, then they will see all 'Binding' as a

single topic area, and not wish to differentiate by using 'Data Binding' as something set aside on its own.

Let us take a look at how our first simple class called 'PersonName2' looks when we give it the full DP registration treatment.

Study the following image very closely :-

===========================================================================================================================

In order to realise what is required when we construct other new custom classes, we need to take special attention

in the image displayed above, to five lines. Look at numbers 117, 168,169, 171, 172, these show all of what is required.

If one or more properties are to be registered with the DP system, then the custom class itself MUST inherit from the

'DependencyObject' class. It took me a while to figure this out as SDK docs and book material was lacking :(

Represents an object that participates in the Silverlight dependency property system.

DependencyObject is the immediate base class of several other important Silverlight classes, such as UIElement,

Geometry, FrameworkTemplate, Style, and ResourceDictionary.

Now lets take the lines 171 & 172 as a pair together - these add a Field to the class, and of name 'DoBProperty'.

It is convention to add the 'Property' to the actual name of the property, in this case 'DoB'.

The registration is done by a static method which takes as parameters the name, the type of the property, the type of the class,

and an optional default value. Obviously, the first three will be needed in the DP dictionary, so as to differentiate the registration

from any other present there, or to be added subsequently.

The last pair of lines from the five are using the name of the new Field to set and get suitable values.

It Seems to me a good idea to keep the registration of the property next to, or close to, the property definition itself, along with the

access/assign or get/set details.

The actual syntax of the five crucial lines to make a DP class which can register properties, seems clear enough from this example.

We should be able to copy and adapt what we seen to do other tings for us.

Using our DP 'Custom' class :

Now that we have a custom class of data object, let us see how we can now use it to make a collection.

Study the code in the following image :-

=======================================================================================================

You will see after checking out the above image that we now have a 'NameList2' class, which is a collection of

our DP class objects, of type 'Personname2'.

Let us see the code which allows us to use an instantiated 'NameList2' to create a 'View' wrapper of the type

'PagedCollectionView'.

PHH - 12th. April 2011.


What Adam Nathan has to say

It is most instructive to see what is written by Adam Nathan at the start of Chapter 13 in his recent book on

WPF 4.

Read this through both carefully, and thoroughly - then read it again !

[ >> In WPF, the term data is generally used to describe an arbitrary .NET object.

You can see this naming pattern in terms such as data binding, data templates, and data triggers.

A piece of data could be a collection object, an XML file, a web service, a database table, a custom object,

or even a WPF UI element such as a button.

Therefore, data binding is about tying together arbitrary .NET objects.

The classic scenario is providing a visual representation (for example, in a 'ListBox' or 'DataGrid' ) of items in

an XML file, a database, or an in-memory collection.

For example, instead of iterating through a data source and manually adding a 'ListBoxItem' to a 'ListBox' for

each one, it would be nice to say, "Hey, 'ListBox'! Get your items from over here. And keep them up to date,

please. Oh yeah, and format them to look like this."

Data binding enables this and much more. << ]

I thoroughly recommend you acquire a copy of this text on WPF, it contains a LOT of good stuff.

PHH - 16th. April 2011.


Vulcan code - Custom class

Enter topic text here.


Chapter 17 - Sorting, Grouping, Filtering

In this chapter and related sections, let us get a few basic things straight.

When we have a data displayed in a grid or list based UI element, the facility to Sort, Group, and Filter,

is provided by the 'View' class - the wrapper around the data collection, which is often an Observable

Collection. This is also true for WPF as well.

If we examine the SDK documentation for the PagedCollectionView (PCV) class we see the following :-

==================================================================================================================================================================

These are some (just over half) of the properties of the PCV class.

As dotNet goes, this is not a large or huge class by any means.

Quick Summary so far :

So if we wish to provide (or allow) Sorting, Grouping, or Filtering, then we need to use the "PageCollectionView" for Silverlight,

and the "ICollectionView" (or similar) for WPF.

The 'View' is also used for record navigating but this aspect is covered thoroughly in the next chapter, number 18.

PHH - 13th. April 2011.


Sorting

Looking at Some Success :

Before we move on to look in depth at the detail of how to script and code 'Sorting', let us see a couple of demo

apps in action - see below :-

The image above shows a 'DataGrid' element which is sorted on three columns.

If the property called 'CanUserSortColumns' of the grid object (not the 'View') is set to TRUE as seen below :-

====================================================================================================================

Then the column headers may be clicked to manually set the sort order required.

If this attribute is set to FALSE then the order can only be sorted using dotNet code. We shall see how

to apply both in the details below.

Checkout the above image to see and confirm that the main sort order is LastName descending - so all the 'Moore' guys

appear together.

Then the second sort 'key' is the FirstName column ascending.

Finally, the third sort 'key' is Age ascending, as seen in the three Andrew Moore records - 7 through to 27.

So the result as shown is a multi key sort using three keys. We say that the keys run from most significant through to

least significant.

Manual Application of the Keys :

Total success with manual application of column selection for sorting depends on, you the user, knowing that if the Shift

key is held down before any clicking of the column headers, we can set a "multi key" sort.

The Silverlight 4 book I am working with (by Beres, Evjen and Rader) also say t he Ctrl key - but that does not work on my

UK desktop system - generally standard setup of most things I would say.

Obviously, if you need to hold down the Shift key for the duration of the multi selection, then a single header may be clicked

more than once, so as to get the correct Asc/Desc option.

However, do realise that the order of the header selection is critical. The first one to be selected is the 'Most Significant' and

the last one the Least Significant'. I have not quite 'sussed' it out yet BUT, I think you need to clear previous sort selections by

a single click in your most significant column (BUT with no Shift key being pressed) then hold down the Shift key and apply

the sort in chosen order.

It would appear that the sort can be changed later, as long as the Shift key is first depressed. So the Asc/Desc of any of the

keys can be changed after previous application of a multi key sort. You just need to be careful, and to get some practice too ;-)

Below is my attempt :-

Check the Moores, and then the Andrews, and their ages too !

Then by no Shift press and a click in the Age column (or two) we get this below :-

Yep! this says that Colin is an old man ;O))

Let us now move on to see how to do this in code.

Coded Application of the Keys :

Once we get the idea that the property of the collection view called 'SortDescriptions', which is a collection of

SortDescription (SD) objects (not surprisingly), has to contain ONLY those objects required for a single or multi key sort,

then it all becomes quite easy.

Before we add any new items to the sort description collection it is a good idea to empty, or clear, the collection.

Checkout below how we then create and add two new SD objects to this cleared collection :-

===============================================================================================================================================================

So from the above image we can see that the most significant column in the sort is the 'FirstName' one, and then

the least significant is the Age column.

I then went to manual mode, press and held the Shift key, and clicked once in the Age column header - this is

what I got :-

===========================================================================

So all that has happened is that the order of the Age has been reversed. See the three Andrews once again.

No Sort Order ? :

It would appear that the only way to clear (or remove) any sort once it is selected and in place, is by providing a

push button which has an event handler which applies the code to 'Clear()' the collection of sort descriptions.

I can't find a keyboard way to do this.

Let us now add a suitable push button, and the script and code to make it work.

=======================================================================================================

And now the code to do the work, which is in the 'code behind' file - check this out :-

=======================================================================================

Yes, it couldn't be simpler ;-)

Selecting Sorts from a Drop List :

It seems both a suitable and a desirable thing to do, to want to be able to select from a combo box one of a

handful of possible sort orders.

For one thing, it is easier to apply more complex orders which may be tricky for a user to apply manually.

Before a particular sort can be applied, we first need to fill our drop list with suitable items.

We will resist the urge to do it the simple way, using stings and then applying a multiple switch (CASE statement).

It is quite easy in .NET 4 to actually have a drop list of SortDescription objects, which we bind to the ComboBox as

an ObservableCollection.

Let us see what the method 'FillComboBox' looks like - see the image below :-

=========================================================================================================

As you can see from the image above, it is nothing startling, or difficult. Just notice line 93 where we set

the item to be seen as selected in the UI element at startup.

If we examine the XAML script for the ComboBox element we see a few useful ideas which we may well be able

to use in the future, with other projects.

First of all, study the following image script thoroughly :-

===============================================================================================================================================

As well as noticing the event we have chosen to handle - probably the commonest used for ComboBox elements - we

have an interesting data template to make the visual effect of our drop list much better.

Lets look at how the drop list looks at runtime - see the image below :-

Notice how the list items appear, there are actually three TextBlock elements, placed within a StackPanel and arranged

in a horizontal fashion.

By doing things this way we can have two different property values in the one item line, as well as having different font and

colour attributes set as well.

The SortDescription class is a very simple one and it has only three properties, as shown below :-

====================================================================================================================================

You may spot that we have used the first and the third in our stack panel with the concatenated TextBlocks.

So to complete this section, we need to see what the even handler method does when the selection is changed in the drop list.

Check this out for details :-

==============================================================================================================

The answer is surprising little !

After checking that the drop list has had a selection made, and that the list is not empty, we clear the old sort order on the

'view' object,

One line of code is then needed to cast the selected object to provide us with a SortDescription object, and this is then added

to the empty collection.

Please note that this approach is only any good with single key sorts, but could be adapted to provide multi key sorting.

If we needed multi key sorting then we could store a set of collections, each one being made up from one or more SortDescription

objects. We may need to make the collection a custom class, so that we could also store and use a name and description

property.

Enough for now, let us move on to the next section.

See you there ..................

PHH - 13th. April 2011.


Grouping

Now that we have seen that a Sort is applied from a collection, or set, of 'Descriptions', we will quite

quickly get our head around the fact that the Grouping of records is also a similar set, or collection.

Study carefully the code in the following image :-

=====================================================================================================

Once again we see we can (and need to) clear the previous contents of the collection, before we start to add

items to make a new collection of group descriptions.

And also, once again, the first object added to the collection is the most significant one - so we have the rows

grouped first by 'LastName', and then sub-grouped by 'FirstName'.

Viewing the results of this grouping - checkout the following image and its details :-

The first thing to notice is that we have four main groups and that these have all been collapsed. I did the collapse

manually, but it can be coded if we require it to be so at runtime. The icon symbol indicates collapse.

Now if I click on the right pointing 'wire' triangle to the LHS of 'Parker' we expand that group, and only that group.

This is what it looks like - see below :-

==========================================================================

Let us now select 'Ben' and try to expand his data with a header click - see below :-

What do we notice ?

Well, there is an indent to the second group header, and the headers are displayed in different colours - both

background and foreground.

The group header does not include any detail as to which column or data field was used.

Since we only provided a couple of code lines to specify the group and subgroup, we must look now in the

XAML script to see what we have that is displaying the details as shown above.

Study the following image carefully to see the relevant script lines :-

=======================================================================================================================

All we have to do to colour our group headers and set the indent value, is shown in lines 30 through 45.

If I comment out these lines we can see the default settings - see below for details :-

As you can see in the above image, the grey of the header rows does not stand out very well at all. However,

we do have a default indent.

Notice too that in the image above the header text contains the property name, because it has not been turned

off by setting the 'PropertynameVisibility' to 'collapsed'.

So removing the commenting, and changing the indent value to 25 we see the following when the app launches :-

*** Note *** that it now looks cleaner due to the header text being absent from view.

Moving on - More Features of Grouping :

In the sample from the SDK - actually the 'Sample Browser' - we can see a push button facility to allow the user

to collapse and expand (fully) the various groups of the display. See this detail in the image below :-

========================================================================================================

So let us know try and add this simple facility to our demo example, before we try to 'improve' it ;-)

Adding the 'Expand All' button :

By now you should have the skills to be able to add your own push button to the form and also add a default event

handler by clicking the drop list from the intellisense in the XAML editor.

Shown below is what I have just added in the editor :-

==============================================================================

And in the code behind file we see both the stub of the handler method, and also the code I have copied and adapted

from the sample in the SDK.

Checkout the details of this image :-

=========================================================================================

Okay, not real rocket science, but no doubt it does the job fine.

Let us launch the app, manually collapse ALL of the groups and subgroups, and then click the button to

see what we get ;-) Tip ! - collapse all the subgroups first.

Here goes ...... well you will have to take it from me that mine works just great.

Adding the 'Collapse All' button :

This is almost the same as before, when we added the 'Expand' button.

This is what I now have in my editor - see below :-

===================================================================================

And to go with the event association with the named handler, here is the stub of the handler method,

once again filled by code from Microsoft SDK sample, with my adaptions :-

=========================================================================================

You will notice that line 151 in the script is new to what we did previously. This has been added so that there

is not any detail left out of sight in the scrolled area. You may be aware that for years in API and WinForms stuff

it was possible have a scrolled area / section which appeared to shown nothing, and contents were hidden out of

sight ;-) One of those 'gotchas' we call 'experience' ;0))

You may think you can do without it (line 151) and this little example seems OK with it missing - BUT, for many

other and larger / complex cases, it will catch us out. So get used to including it in your standard coding.

You will have to try this for yourself, just to see it works. It does have a good feel to it - clicking and expanding

or collapsing.

Group by Group - Expand and Collapse :

You may have realised by examining the code that we could possibly have separate buttons to work on just the main

group and just the subgroup. Well look at the code shown below :-

===============================================================================================================

This shows the line 155 of script, which will close the main group - that is the first item to be added to the collection

of GroupDescription objects.

Notice that we do need to cast the selected item from the collection. This does work, and looks like this once a fully

collapsed state has been created and then the button clicked :-

PHH - 13th. April 2011.


Filtering

Filtering is coded differently to Sorting and Grouping.

Because only one filter condition can be used at any one time, we do not have a collection for filter

objects of any kind.

Instead the SDK says this about the 'Filter' property of the 'PagedCollectionView'.

Gets or sets a callback that is used to determine whether an item is suited for inclusion in the view.

The 'setting' of the property looks like this below :-

==============================================================================================

The method being 'called' here has a name of 'FilterNoBirthDate'.

And the SDK says this about any filter method :-

A method that is used to determine whether an item is suited for inclusion in the view.

Let us now look at the format of this method to see the general form it takes :-

============================================================================

Basically, the method code determines if an item is to be included, or not. Hence the returned value is of type Boolean.

Here is what the SDK has to say - and note the 'ICollectionView' even though this is under the 'PageCollectionView' section !

Remarks :

The Filter is a callback set by the consumer of the ICollectionView and used by the implementation of the ICollectionView to

determine whether an item is suited for inclusion in the view

To be honest with you, when I first wrote the above method I seemed to get my logic 'back to front' as far as the result was

concerned. By this I mean that the title of the method, and the items it included in the display set, were contradictory !!

So at the moment all I can say is be careful in your method naming, and always test out what you write to see it includes

just what you require.

So at the moment my code above reads that if the return is TRUE it filters out those with no birth dates supplied, and so they

have the default of 1900,01,01.

However, in fact it is setting a value of TRUE so that the item is included in the 'View' according to the SDK comment above.

Hence line 73 test for dates greater than the default, and then sets a TRUE return.

I told you it was tricky to get it right - simply do it, test it, and then adjust it - is my best advice ;-)

Because we are writing our own dotNet code, we can make the comparison condition as complex as we like - no problems there.

Filters - Applying One of Many :

I am aware that most developers will be saying from the outset, ".. but I want my users to be able to apply different filters .." so

to solve that problem here is a simple way as a start to answering this particular query.

Let us see the code in action first - see below :-

In the above images we can see that we have a drop list (combo box) element with some suitable names of filters.

We have selected the second one in the list which is 'Older'.

Notice that the 'view' immediately adjusts, and only those guys older than 38 are displayed.

Seeing How this Works :

It is probably best if we start with the XAML script and the 'ComboBox' entry - see below :-

===========================================================================================================================

Yes, I said it was simple - we have simply put a few suitable names in the drop list.

However, the important part is that we have added to our 'ComboBox' declaration an attribute to react to the 'SelectionChanged' event.

As we read the script we see we ought to have a method in code called "myCB1_SelectionChanged".

Let us take a look at this method seen below :-

===========================================================================================================================

Just as a precaution we are checking for an empty drop list, so as to avoid errors.

So what does our 'SetFilter' method look like ? See the image shown below :-

====================================================================================================================

Yep! nothing clever at all, just a multiple switch so that we set the appropriate filter property for the selected filter name.

Let us look at the code for one of these, say a more complex condition, that of 'Long Names' - see below :-

=================================================================================

Finally, let us see how this looks when selected - checkout below :-

Note that we have used the details held in two columns (or data fields) to determine a 'Long Name'.

It may also be useful to see the 'Clear Filter' code which is run in response to clicking the appropriate push button.

Here is what we are using in this app :-

========================================================================================================================================

Time to move on I feel.

See you in the next section where we look at navigation through the data records with the facilities provided by the collection

view class methods and properties.

See you there ............

PHH - 13th. April 2011.


Chapter 18 - Navigating a View

PHH - 14th. April 2011.


Chapter 19 - Life without Triggers !

=========================================================================================================================================

PHH - 19th. April 2011.


Appendix A - SDK Sample Browser

This is the best news I have heard in all the time I have been programming, developing, coding, and now scripting !

Because of the Silverlight technology, we can have direct access at a distance to Microsoft's whole bank of sample

Silverlight apps and demos.

Not only do we get working examples of script and code behind for each, but of course they run in real time too ;-)

Here is the live link to the home page of Microsoft's website :-

[ http://samples.msdn.microsoft.com/Silverlight/SampleBrowser/#/?sref=HomePage ]

==========================================================================================================================================

[ http://www.silverlight.net/content/samples/sl4/toolkitcontrolsamples/run/default.html ]

===========================================================================

=============================================================================================================================

=============================================================================

=================================================================================================================

=================================================================================================

===========================================================================================================================

==================================================================================================================

PHH - 31st January 2011.


working script and code

 Top Previous

<Canvas>

<StackPanel>

<TextBlock

FontFamily="Verdana"

FontSize="32"

FontWeight="Bold"

Foreground="SteelBlue"

Text="Scaled Text" />

<!-- Scale the text width using a ScaleTransform. -->

<TextBlock

FontFamily="Verdana"

FontSize="32"

FontWeight="Bold"

Foreground="SteelBlue"

Text="Scaled Text">

<TextBlock.RenderTransform>

<ScaleTransform ScaleX="1.5" ScaleY="1.0" />

</TextBlock.RenderTransform>

</TextBlock>

<!-- Scale the text height using a ScaleTransform. -->

<TextBlock

FontFamily="Verdana"

FontSize="32"

FontWeight="Bold"

Foreground="SteelBlue"

Text="Scaled Text">

<TextBlock.RenderTransform>

<ScaleTransform ScaleX="1.0" ScaleY="1.5" />

</TextBlock.RenderTransform>

</TextBlock>

</StackPanel>

</Canvas>