Thursday, April 3, 2008

Actually Using Multi Scale Images in Silverlight - DeepZoom and Mouse Wheel Support with only Silverlight Code...

Using Silver Dragon is pretty straight forward. We start with adding a multiScaleImage to our Xaml and then pointing it at our collection 'bin' file. Generally we would take the output from DeepZoom and then input it into our web project, that we are using to build out our Silverlight application. Then we point the source to the info.bin file. In the case of the collection we built in the last sections it will look something like this:

<MultiScaleImage x:Name="SilverdragonImage" Source="/collection/info.bin" Height="400" Width="400"/>

With just this, when we run our project the MultiScaleImage will animate the zoom of our collection up to the point of being constrained by either the height or width whichever occurs first. Using our collection we created in DeepZoom we then using a default empty solution with only the MultiScaleImage added we will get this figure on the screen.

At this point we can bind events to our MultiScaleImage. The mouse events are typical but we might want to use some of the additional events such as ImageOpenSucceeded, where we can fix up the UI as needed relevant to the image. Once everything is wired up our Xaml.

<MultiScaleImage x:Name="MyFirstMultiScaleImage" Height="400" Width="400"
MouseLeftButtonDown="MyFirstMultiScaleImage_MouseLeftButtonDown" MouseLeftButtonUp="MyFirstMultiScaleImage_MouseLeftButtonUp" MouseMove="MyFirstMultiScaleImage_MouseMove" MouseLeave="MyFirstMultiScaleImage_MouseLeave"
ImageOpenFailed="MyFirstMultiScaleImage_ImageOpenFailed"
ImageOpenSucceeded="MyFirstMultiScaleImage_ImageOpenSucceeded" />

This shows the key events on the MultiScaleImage element we might want to wire up but for zooming in and out we might want to consider using the scroll events, for the mouse wheel off of the window object to give the control rich functionality for users. This will require a bit of hacking in our object so we don't have to use JavaScript in our page. Then we will actually build our class such that it will all be Silverlight code, which by design doesn't support the mouse wheel events. This primarily has to do with the fact, that different browsers expose it differently where we can overcome this in using client side ECMA code, that will be generated in our Silverlight application. Let us start with the click related functionality. For some of the functionality we are going to do, we will need to include another 'using' reference at the top of our application source or C# user control page. The using needs to look like this:

using System.Windows.Browser;

This gives us access to the DOM bridge we will use. To build out all functionality we will use we will need to add some private members and flags for state tacking and references. The initial values we need include the following listing:

public string Source = "SilverDragon/source images/OutputSdi/collection/info.bin";
private bool _IsMouseDown = false;
private bool _IsDragging = false;
private Point _LastImagePoint = new Point(0, 0);
private bool _ErrorState = false;

The first one is used as our Source for MultiScaleImage, the next two are obvious flags for conditions in our application and a point object to show us what the last 'point' was, and the last one is if the class is in an error state and broken. This all need to be members of our user control, and you can tell that is the case by the use of the key word 'private' in front of the declaration. Next we need to make sure the constructor has what it needs to set up the application into the state we will need: The constructor should have the following code listing:

if (Source.IndexOf("http") < 0)
{
string URL = System.Windows.Browser.HtmlPage.Document.DocumentUri.AbsoluteUri;
Source = URL.Substring(0, URL.LastIndexOf('/')) + "/" + Source;
}

MyFirstMultiScaleImage.Source = new Uri(Source);
HtmlPage.RegisterScriptableObject("MySilverlightObject", this);

Here we will make sure the source has a hard URL and if not we will complete it assuming the relative path is relative to our execution location on the server via http. With this we can now look at the actual binding events we use.

void MyFirstMultiScaleImage_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (!_ErrorState)
{ MyFirstMultiScaleImage.CaptureMouse();
_IsMouseDown = true; _IsDragging = false;
_LastImagePoint = MyFirstMultiScaleImage.ElementToLogicalPoint(e.GetPosition(MyFirstMultiScaleImage));
}
}

Here we check to see if the application is in its error state and if not we can perform the event. First we capture the mouse in case we are going to do any panning and we test our event flags for mouse down and dragging. Then we get the last point and save it if we are panning and/or zooming in or out. Next let's do our Mouse up with this listing:

void MyFirstMultiScaleImage_MouseLeftButtonUp(object sender, MouseButtonEventArgs e){
if(_IsMouseDown && !_ErrorState)
{
if(!_IsDragging)
{
Point MyPoint = MyFirstMultiScaleImage.ElementToLogicalPoint(e.GetPosition(MyFirstMultiScaleImage));
double ThisFactor = (Keyboard.Modifiers == ModifierKeys.Alt) ? 0.5 : 2;
MyFirstMultiScaleImage.ZoomAboutLogicalPoint(ThisFactor, MyPoint.X, MyPoint.Y);
}
MyFirstMultiScaleImage.ReleaseMouseCapture();
}
_IsMouseDown = false;
}

In this case we can see we checked that the mouse down flag is set and the error state is not true. If those are correct we also check to see if we have been 'dragging,' and if so we grab the current zoom point, calculate a factor based on the alt key, then perform a zoom operation, release the mouse capture and set the mouse down flag to false. This method then deals with either what was the mouse down event or if there was the drag operation or scroll operation. Next we will actually do our mouse move event with this listing.

void MyFirstMultiScaleImage_MouseMove(object sender, MouseEventArgs e)
{
if (_IsMouseDown && !_ErrorState)
{
_IsDragging = true;

Point p = MyFirstMultiScaleImage.ElementToLogicalPoint(e.GetPosition(MyFirstMultiScaleImage));

Point delta = new Point(p.X - _LastImagePoint.X, p.Y - _LastImagePoint.Y);

MyFirstMultiScaleImage.ViewportOrigin = new Point(MyFirstMultiScaleImage.ViewportOrigin.X - delta.X, MyFirstMultiScaleImage.ViewportOrigin.Y - delta.Y);

}
}

Here we first test for the mouse down and error state flags. If they are correct we start our drag operation by setting the value to true. Next we then grab the current point and calculate the delta point, from the last point and then set the viewport origin on our MultScaleImage. Nice and simple right? Now lets add a few methods to help deal with error conditions. First the ImageOpenFailed event that fires if something goes wrong with the source using this listing:

private void MyFirstMultiScaleImage_ImageOpenFailed(object sender, ExceptionRoutedEventArgs e){ _ErrorState = true; }

All it needs to do is set the error state flag if there is a source failure, which will basically set the application into an error state. We could add more code here to do things like switch sources, or something else if we wanted to. Next on the off chance that we are in an error state and the image open succeeds then this method will set the application back into a good state with this listing of the Image Open Succeeded event:

private void MyFirstMultiScaleImage_ImageOpenSucceeded(object sender, RoutedEventArgs e){ _ErrorState = false; }

This sets our application back into a happy state where we can perform deep zoom operations, but next we need to deal with the mouse leave event so we don't leave our MultiScaleImage in a weird state. We do this by using the mouse leave event like this listing:

private void MyFirstMultiScaleImage_MouseLeave(object sender, MouseEventArgs e)
{
_IsDragging = false;
_IsMouseDown = false;
MyFirstMultiScaleImage.ReleaseMouseCapture();
}

Here we reset both; the dragging and mouse down flags and release the mouse capture if it is captured, so we can move on. This basically completes the functionality that Silverlight 2 supports, but we can build mouse wheel support with the following section

HACK - Mouse Wheel Events in SL and with the MultiScaleImage

The 'Mouse Wheel Events' are not really supported. This is in large part due to disparity between how the different browsers support getting this event into a plug in. That however being the case also makes it worth our while to look at the fact that the mouse wheel support inside the context of the scripting engine for browsers is fairly well built out such that we can build a client side solution that feeds into our Silverlight application. However this approach feels like to much of a hack, and we can build out this same hack and make it all in our Silverlight. This still however is a hack, but it really is a lot more pleasant when the Silverlight class can wire all this on its won without us having to build out anything special in our web page (html, asp or whatever). Remember we already added the using statement so we could use the DOM bridge? Now let us start by adding a couple more properties at the top of our class with this listing.

private static string _MOUSEWHEELHANDLER_JS = "function OnMouseWheel() { ($get('Xaml1')).content.MySilverlightObject.MouseWheel(window.event.clientX, window.event.clientY, window.event.wheelDelta); } ";

private static string _MOUSEWHEELEVENT_JS = "window.onmousewheel = document.onmousewheel = OnMouseWheel; if(window.addEventListener) { window.addEventListener('DOMMouseScroll', OnMouseWheel, false); }";

Gasp, I know many of you will note that these two values contain ECMA script. Since Silverlight supports what we need and scripting does, but we don't want to be writing everything in the client, this approach allows all to be built out in our Silverlight code and it makes the class more easily reused. Next we need to add a little private method that does our black magic here with this listing:

private void InsertECMAScript(string JavaScript)
{
HtmlElement Script = HtmlPage.Document.CreateElement("script");
Script.SetAttribute("type", "text/javascript");
Script.SetProperty("text", JavaScript);
HtmlPage.Document.DocumentElement.AppendChild(script);
}

I know this really might give some people heart burn, but it really makes our DeepZoom class more portable. In this case anything we pass into this element will get tacked onto the end of our web page HTML DOM and since it is script up front it gets executed. We use this function in our object constructor like this:

InsertECMAScript(_MOUSEWHEELHANDLER_JS);
InsertECMAScript(_MOUSEWHEELEVENT_JS);

Again, this is really giving some people heart burn, but I think it is cool and much less hassle. One thing to note though is we still didn't add our Mouse Wheel event in our code. Todo this we can add this event handler as in this listing:

[ScriptableMember]
public void MouseWheel(double x, double y, int delta)
{
if (!_ErrorState && !_IsDragging)
{
double ZoomMultiple = (delta < 0) ? 1 / 1.33 : 1.33;

Point p = MyFirstMultiScaleImage.ElementToLogicalPoint(new Point(x, y));

MyFirstMultiScaleImage.ZoomAboutLogicalPoint(ZoomMultiple, p.X, p.Y);
}
}

When we compile it and run it, we now get the click zoom in and out behavior. We can use the alt key when we zoom out on click, and the mouse wheel event is tied into our MultiScaleZoom and it is a reusable class.

Tuesday, April 1, 2008

WCF and Silverligth 2 - Beta 1 and automated builds

One issue I ran into recently was the fact that currently the Silverlight 2 autogenerated client code for WCF services is autogenerated. This is not a big deal typically, but here is where I found some issues... (actually it wasn't me but this guy Sina that found the problem and some one on Mike H's team that explained it) but this is what was found.

We are doing this pretty big silverlight application that is pretty much a shrink wrapped quality solution. Part of the implementation of this is a complete automated build system for QA and part of that was the fact that the production environment is a huge hands off big no touching sort thing.

In this particular application we have a number of WCF services that we are talking to, that are local in the web solution along with the silverlight application. When you run this in Visual Studio it works well. When we deployed it we noticed we had to deploy the solution, re do the references to the deployed WCF service and then deploy again. a bit of a pain but in and automated scenerio using msbuild and the like and you have no idea what the url will be, this is extremely problematic.

We also found a nice service client config file with the url settings for the server etc in the compiled xap but when changed this didn't seem to do anything. Much to our sadness we found out that we might look for this in the next version and the file though created was ignored. The solution that hopefully will go away in Beta 2 is to over-right all our constructors and pass in a value we configure in the web.config... Basically something like this:

ServiceClient MyClient = new ServiceClient( new BasicHttpBinding(), new EndpointAddress( new Uri(SomeConfigValueAsString)));

basically overright which constructor is used and pass in the value that would normally be compiled directly into the dll. A hack I know but it works until we get that beta 2 and we can still use our WCF service.

New Look and Feel

With much sadness I have updated the core template for the hackingsilverlight.net site. Before the site used a nice little bit of code that denied the users w/o silverlight from getting anything. The new template although bazardized from the nice template done in Blend that Ariel sent me is much cooler and doesn't remove all the text content if you don't have silverlight. In fact if you don't pay close attention you might not even notice that it is using a Silverlight header. :)

Wednesday, March 26, 2008

Silverlight Spy

talk about hacking some silverlight :) this is a cool tool

"Silverlight Spy provides detailed XAML inspection of any Silverlight application. Use the built-in browser to navigate to a web page. Silverlight Spy will automatically pick up any Silverlight application embedded in the page and display..."

http://www.silverlightspy.com/silverlightspy/

Tuesday, March 25, 2008

Foundation Blend 2 - Building Applications

I work with this guy Victor that finished his book first. Its more a Blend centric book but promisses to be really good. Of course not to distract anyone from buying my book when it comes out :) but with much ado here it is:

http://windowspresentationfoundation.com/index.html

Thursday, March 20, 2008

Full Screen Silverlight 2

So I"m porting my old silverlight bits to silverlight 2 and I noticed I didn't see much are doing this so I thought I would post this up here for everyone. So in this case I'm making a media player control that I can drop in where ever I need it but I want it to be able to go to full screen. In my class I create a method like this:


private void TopElement_OnFullScreenChanged(object sender, EventArgs e)
{
SizeUI();
}

right now this calls a method that mucks up my UI depending on control size so when it is in full screen it just uses all the realestate. In the class constructor I bind this method to the host like this:


Application.Current.Host.Content.FullScreenChanged += new EventHandler(TopElement_OnFullScreenChanged);
I then create a bit of xaml that points at this method:


private void Canvas_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if( SLHost.Content.IsFullScreen )
{
SLHost.Content.IsFullScreen = false;
}
else
{
SLHost.Content.IsFullScreen = true;
}
}

which that actually is dependent on this being a private member:


private SilverlightHost SLHost = new SilverlightHost();

with that nice a simple bit of code I have full screen mode :)

Thursday, March 13, 2008

Using Expression DeepZoom

The key tool for building out MultiScaleImages we will use in Silverlight is Expression DeepZoom. DeepZoom is a Simple tool like Encoder for example that allows you to import images and produce the multi-layer image collections and tile structure used by DeepZoom (MultiScaleImages) in Silverlight to produce the coolness we are looking for.


DeepZoom (talk about double entendre) then creates a DeepZoom Project lets you import all the high resolution images you want to use. Then you can compose your collection of images and then it will export and build all of your multilayer image collections, tiles and other bits as configured. With that then we can embed these into Silverlight work with multilayered images.
We learn how to use the application by opening Expression DeepZoom and getting familiar with the user interface.


Currently the interface is pretty simple. We have our splash screen that pops up. That shows existing projects or lets you open new ones etc. We also can see the tabs which are basically the 3 steps to building a Multi layered image collection and getting it ready for Silverlight. From the top file menu we can open the project dialog.


Once we give our project a name and select the type (Seadragon Project) we then can start adding images to our multi-layered image collection. On the import tab in the UI we can see we have a view area and then a scrolllist of our images. At first this will be blank and at the bottom we have a button called 'Add Image.' If you click the 'Add Image' button you can use the standard windows API file dialog to find a cool high resolution image that you want to multi layer. If you add several you will see them on the design surface.


Now that we have added some images we can start arranging them in our collection. Start by click on the tab '2. Compose' at the top of the interface. Then you can drag the images from the right on to our design surface.


Let us take a look at the interface. At the top of the UI we can see a tool bar at the top and there are 5 tools which by default will have the first one selected. The first three icons represent the cursor state on the compose view of the application. The default is for dragging our icons onto the surface. Selecting second icon you can drag the design surface.


You can see how the map in the lower left of the composition surface has moved showing what the pan functionality looks like and this map shows you where on the surface that you are. The third icon on the compose tool bar is for zooming. This allows you to drill into any given location on the composition surface.


Looking closely we can see the drop down menus for the last two icons on the composition tool bar. You can see the second icon from the right is alignment items (i.e. left, right, top, bottom etc). if you select one then all your images get laid out in the collection accordingly. The menu for the last button that distributes images horizontally or vertically.


Once we get all our images on our composition surface we are ready to export our collection. There are a number of settings but for DeepZoom in Silverlight we are good with just having a location and exporting. We do this by clicking the export button.


DeepZoom then builds our Silver Dragon (SDI) file and builds out all over tiled images. If we are just going to use it for Silverlight and are using one image we can just grab its corresponding structure including the .bin, xml and the tile jpg's. Now we are ready to actually do Seadragon, er I mean SilverDragon, er I mean DeepZoom(MultiScaleImages).

Tuesday, March 11, 2008

ItemsControl, ListBox and DataGrid's, oh my

The ItemControl's coolest use is to layout 'items' via an item template using data binding to a collection. As a functional control this really requires more than just some Xaml and in fact we will walk through the process in order so we never have Visual Studio throwing some errors. In your page behind you will need to make sure you include these libraries as show here:

using System.ComponentModel;
using System.Collections.ObjectModel;

This gives us access to ObservableCollection and INotifyPropertyChanged so we can build out our data. We will create a method that create our collection but first we need a base classes for our data. To start with we need to create the Data class first like this:

public class Data : INotifyPropertyChanged
{
private object _value;
public event PropertyChangedEventHandler PropertyChanged;

public Data(object val) { _value = val; }

private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
}

This inherits from INotifPropertyChanged and we create our NotifyPropertyChanged method along with a constructor so we can pass our value in when we create instances of the class. Since we have a private value we need to expose it publicly so we can then bind our templates to it as used in the items control. So then we add the following code to the above class:

public object Value
{
get { return _value; }
set
{
if (value != _value)
{
_value = value;
NotifyPropertyChanged("Value");
}
}
}

This 'Value' public property is what we will actually bind to. Then we can create our DataCollection that is an ObservableCollection of our Data Class like this:

public class DataCollection : ObservableCollection<Data> { }

Now we have an ObservableCollection that we can bind to. Next we need to create a method that creates or gets the data. Here we will hard code the data into this simple example:

private object GetData()
{
DataCollection MyCollection = new DataCollection();
MyCollection.Add(new Data("One"));
MyCollection.Add(new Data("Two"));
return MyCollection;
}

Let us now look at our Xaml, now that we have our collection and something to create it or fill it with data we need an items control and template to do something with. First we build our template for each item that will be listed in the items control.

<UserControl.Resources> <DataTemplate x:Name="MyDataTemplate" > <TextBlock Text="{Binding Value}" ></TextBlock> </DataTemplate> </UserControl.Resources>

This will bind to the public value of 'Value' as created in our data class earlier. Next we need to actually create the items control. An Items control can be as simple as this:

<ItemsControl x:Name="itemsControl" ItemsSource="{Binding}" ItemTemplate="{StaticResource MyDataTemplate}" >
</ItemsControl>

In this case we set our ItemSource to be Binding and then we use a static resource namely our template. Back to our code we now need to point the items control to the method that creates our collection using code like this:

this.itemsControl.DataContext = GetData();

This can be in our page's or user controls constructor and sets the data context to be the collection of objects as an observable collection that we are building and returning. When we run this we will get a list of items as created in the GetData method much like a stack panel would lay out its children where in this case the default is vertically.

Not terribly impressive but under the covers very cool. What is most cool about it is the key functionality this provides. This can be used for everything from dynamically build menus and other dynamic lists of different kinds and more. To move beyond that we can also use the new control Listbox.

Using the Listbox control

The Listbox control is much like the ItemsControl but we are adding functionality including scrolling and selection rollover functionality. We can style it and using databinding and the like just the same. So using the code from the last section we can change out our Xaml and be ready. To start with add additional elements in the collection in our source this way we have 20 or so elements so we can see the scroll functionality. Then we can remove the ItemsControl and add a Listbox like this example:

<ListBox x:Name="itemsControl" Grid.Row="1"
ItemsSource="{Binding}"
ItemTemplate="{StaticResource MyDataTemplate}" />

So by adding all the extra items to our collection we can really see the big difference between ItemsControl and Listbox control.

With the Listbox control it is easier to implement functionality like select or drop down functionality that users see in other technologies. Now to take this even one step further lets look at DataGrid.

Using the Datagrid Control

The Datagrid is used much like the list and items controls but the datagrid is targeted towards result set functionality. In this case we need to make sure we specify the name space in the xaml. At the top if you use Visual Studio and start to create a name space it will give you a list and you want to select the 'System.Windows.Control.Data'. You can give your 'namespace' any name you want but since it's a Datagrid we are talking about I'm partial to 'Data' as a matter of course. So lets assume the same code base as the Listbox we did earlier, then rip out our 'ListBox' and then add this bit of Xaml

<Data:DataGrid x:Name="itemsControl" AutoGenerateColumns="True" ItemsSource="{Binding}" />

When we run this we get a nice data grid like the ListBox but we get column names. We can of course re-template this to look pretty much any way we like but default will look pretty much like any data grid control you might see in winforms.

As you can see its pretty much the same as the ListControl and ItemsControl but Columns are added and we have set it to auto-generate the columns.

Wednesday, March 5, 2008

Download links from MIX 08 - Silverlight

here is a link to a list Tim pushed to his blog with all the download links:

http://blogs.msdn.com/tims/archive/2008/03/05/download-links-for-mix08-announcements.aspx

Silverlight MIX Announcement(s)

In the keynote today Scott G annouced SL 2. is publicly available. very cool. my favorite part whas how much they showed our Entertainment Tonight work in Silverlight. among my favorite features annouced include (I will skip all the new bits Scott put out on his blog last week):

* support for Silverlight on MAC, Windows, Linux and Mobile devices
* improved preformance especially dynamic adaptive streaming and bit rate throttling, including IIS features to support to provide bit rate throttling.
* Silverlight Add templates in visual studio
* Burning Silverlight right into video using ecoder 2
* Multi-language including Silverlight in Python
* Rich WPF UI framework (layout, databinding, skinning and styling system)
* Robust networking (post, SOAP, WCF, sockets etc.)
* LINQ and Databinding
* Local Store and cache between browser sessions
* Controls include: data grids, list box, sliders, radios, buttons calender and date picker controls, checkboxs etc.
* all controls are being shipped with open source license.
* test framework for silveright.
* control templating stucture including the abilty to change animations, and restructure the visual tree
* full intellisense and design experience in VS
* DeepZoom.... formerly Silverdragon formerly SeaDragon taking smut to the next level allowing arbitrary zooming to any resolution smoothly.
* Silverlight Sharepoint bits to make it easier to put silverlight web parts in sharepoint

SeaDragon (DeepZoom) really is cool with the 2billion pixel size images... :)

IE 8.0 first impressions

So one of the first things we are seeing in the MIX keynote is IE 8.0 which seems to be more about standards and helping developers do better work. So far we got some CSS 2.1 support, HTML 5, in proved perf especially with script, more itegrated debugging tools and visual related tools directly in IE if a user wants. there are better tools for users like being able to select text and IE will provide services tools based on the text. That sounds problematic but seeing it work is really cool. And web slices are cool.

beta 1 is available at:

http://www.microsoft.com/ie/ie8/

MIX 08 - Silverlight - Wish you were here...

Ah MIX... its finally here. Hmm... we will see what kind of coolness comes out of mix. The conference starts wed and since it is sooo late that I got back to my room in the Venetian that it actually starts later today. Anyway I digress. Even though the conference started I have learned alot. I spoke with Laurence (another author of the MS press book Silverlight 1.0) about publishers and our up coming books and the like. Plus there was the Silverligth Insiders 'meeting' such that it was at the V Bar. We can to meet some of the guys we didn't know and talk with some of the guys we did. Adam has blue hair and we will see how the rest goes but we still can't talk about too much. Also Nokia annouced that their phones will support Silveright so i think it is safe to extrapolate that MS is going to get it on windows CE. Oh plus the plane ride up... well I guess I have to save the good stuff for after the key note.

Monday, March 3, 2008

No Soap for you! - The No Silverlight Experience

So I'm collecting hacks for my upcoming book, and I must say, here is a simple one, but one of my favorites... LOL!

On my HackingSilverlight.net (the domain not the feed site), I did not have time to worry about the non-silverlight user and in fact chose to be a bit over-the-top towards them. Personally I find it funny, but I know many people think its just plain mean... but really what is someone doing at a Silverlight site if they don't have silverlight? So to save me from work, here is my on-load function...

function OnLoad()
{
Resize();
try
{
if( !Silverlight.isInstalled("1.0") )
{
var parentElement = document.getElementById("BlogContent");
parentElement.innerHTML = "";
}
}
catch(Exception)
{
alert('NO SOUP FOR YOU!...');
}
}


Note the 'innerHTML' which would normally contain the entire HTML block that makes up all the visible content on the page except the install badge... again I found this extremely funny, but alas, with the book coming, I will probably make it play nice.

Thursday, February 28, 2008

Using the Silverlight 2 Xaml StackPanel Element

The next advanced layout element in Xaml is the stack panel. The StackPanel lays out its children either horizontally or vertically without having to define the exact location in the visual tree in Xaml. Take the following listing example of a stack panel.

<StackPanel Width="200" Height="200" Orientation="Vertical" Background="Gray">
<Rectangle Width="50" Height="50" Fill="Green"></Rectangle>
<Rectangle Width="50" Height="50" Fill="Blue"></Rectangle>
</StackPanel>


We can see in this example that we set the size and orientation of the StackPanel. The StackPanel will then start at the root X, Y (0,0) position of its parent by default. Children are then rendered vertically in the panel. Now look at this example StackPanel:

<StackPanel Width="200" Height="200" Orientation="Horizontal" Canvas.Top="200" Background="Gray">
<Rectangle Width="50" Height="50" Fill="Green"></Rectangle>
<Rectangle Width="50" Height="50" Fill="Blue"></Rectangle>
</StackPanel>


In the example we see that the Orientation of the StackPanel is set to Horizontal so its children will be laid out accordingly. When we put both of these StackPanel into some Xaml this is what we get. We can see the first one rendered vertically and the second horizontally.



Using advanced layout, it is easier to create list box functionality or recordsets and using other structures like templates and the like you can pull records data bind and then use StackPanels too easily lay out all the items you need.

Using the Silverlight 2 Xaml Grid Element

"The Grid" is basically just that: a grid with a set number of colums and rows. Elements in the grid must then be placed into a cell within the grid by setting the Grid.Column and Grid.Row property of the element in question. To start using a grid you first need to create a grid node.

Here is a simple example:
<Grid Height="200" Width="200" Background="Red"></Grid>


For us to see what is going on, we set the background value to red and then we set a width and height. The width and height set the boundary of our grid. If we don’t set a top and left value. then grid is laid out relative to the top and left of the parent element that it is in. To use a grid we need to add rows and columns inside of it.

<Grid.RowDefinitions> <RowDefinition/> <RowDefinition/> </Grid.RowDefinitions>


This code creates two rows in our grid, but we still need column definitions to actually use the grid. The following code adds 2 columns, which then gives us a grid of 2 rows by 2 columns which then has a total of 4 cells.

<Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition /> </Grid.ColumnDefinitions>


With a complete grid we just need to add something to it to be able to actually see how it renders. Lets see what happens if we add a single rectangle to our grid.

The following code sample creates the simple rectangle set to be in the second column and the second row; we also set the fill value to green.

<Rectangle fill="Green" row="1" Column="1" />

Now when we render this xaml you will see that the grid columns are rows are zero based. Zero based means that the first column is 0 and the second column is 1.



Knowing that the grid columns and rows are zero based, we expected the rectangle to be in the lower right position. What we also see from this sample is that by default an element fills the entire grid that it was assigned to. To overwrite this behavior, you would just need to set values for theheight and width. This is the same for top and left values where the default will be to be aligned with the top left of the assigned cell.

Using the same grid, lets remove the old rectangle and add this canvas and textblock.

<Rectangle Fill="Green" Row="0" Column="0"> <Canvas Height="100" Width="100" Background="Blue" Row="1" Column="1" VerticalAlignment="Bottom" HorizontalAlignment="right"> <textblock>Hello</textblock> </Canvas>


In this case, the rectangle is in the top-left cell. However, we now have added a standard canvas with a text area. The canvas is set to have a width and height of just 100 and placed in the lower right cell where we also set the horizontal alignment and vertical alignment. We also set the background to blue so that we can see what is going on.

In this next figure, we can see exactly how the grid lays out the combined set of the elements we have added.




We can also set Margin and ShowGridLines on the Grid element as needed. This allows us add both of these elements as needed. If desired, we could also set height on the row definition and width on the column. This allows us fine control of cell sizes as needed, otherwise, the grid will equalize things for the size it has been given.

Besides setting exact values with height and width, we can set them to auto or * as well. Lastly, elements in a grid can also use Grid.ColumnSpan to allow elements to span more than one column.

Cat out of the Bag

So I see that a number of places that are 'official' have talked about some features that will be in the new bits for Silverlight 2.0... SO therefore I think it is ok to talk about these. for example Scotts blog at:

http://weblogs.asp.net/scottgu/archive/2008/02/22/first-look-at-silverlight-2.aspx

So expect to see more coolness starting today.

Wednesday, February 27, 2008

Hacking Silverlight 2.0 for designers and developers

As some of you know, I'm writing a book on silverlight titled, "Hacking Silverlight 2.0" with the help of Manning Press. As some of you may also know, I have not been able to blog too much as of late due to all the super secret stuff on campus at Microsoft. Some day that will stop and I will probably have lots of stuff to post, but in the mean time, I thought I would share the work on the cover of the book. The example of a book cover is a prototype and you can see the entire process Ariel went through to develope the painting we are using for the book cover.

http://www.facebook.com/album.php?aid=25283&l=593e3&id=721326429

Manning, the publisher, has a tradition of putting central European art on the cover... milk maids, stable boys, girls in dress's etc. I could not have something like that. Granted all the art is cool and they do have some interesting bits on the cover of some but I couldn't take the risk of getting a milk maid. So I have something manly and war like and for those that are interested in the painting, here is a little bit about it:

The soldier on the cover is a Polish Winged Hussar a type of Polish Calvary from the 16th Century to the 18th Century. This particular Hussar belongs to the Jordan Family or Domus Giordanous from southern Poland near Krakow. The Winged Hussar Calvary were the best mounted calvary at the time and won most engagements even when outnumbered by huge odds. Case in point, The Battle of Kluszyn against the Russians with 35,000 men against the Polish Crown with just over 6,000 Hussars. Key to this was the armor and heavy weapons and their most common tactic of the charge straight into enemy lines.

Tuesday, February 26, 2008

Silverlight 2.0 Double Click Support

Ok, ok, I'm not giving anything away so don't get too excited. Check back at some later date. Who knows maybe MIX??? That is like next week.

Anyway, recently, I was told that you can't double-click in Silverlight...

So to me this is a bit hard to respond too. Not because Silverlight doesn't support it, but because if it supports single click or, 'OnMouseDown' -- 'OnMouseUp' or anything similar, then we are good. Basic computer science 101 stuff, right? All you need to do is something like this example.

In my code I create a counter for counting ticks. Say like this in c#:

public long LastTicks = 0;

Then in my 'MouseLeftButtonDown' event I have an 'if' statement that basically checks to see if the number of ticks between the last two mouse clicks is less then some defined number like this:


if ((DateTime.Now.Ticks - LastTicks) < 2310000)
{
// double click
here...
}

...and then at the end of the method, we have a line that sets the LastTicks value like this:

LastTicks = DateTime.Now.Ticks;

Nice and simple. This gives us a good solid double-click that we can do with whatever we need. Now in this sample we are using ticks but we could use any date-comparision thing and use seconds, for example, and we would just have to calculate the differential we want to use. For me it was 23.1 million ticks which seemed to work good on my box :)

Now don't go sending me a billion emails on why we don’t use double clicks in web apps. I'm just saying that it can be done, and a number of people asked. I know very well that double-click is not a good plan generally in a web sort of paradigm.

Wednesday, February 13, 2008

Cool Tool Kaxaml

I know this guy Robby that wrote this cool Xaml tool... Kaxaml. It alot like Xaml pad with the split view but the coolest thing is the snippets, Xaml scrubber and intellisence. check it out at

http://www.kaxaml.com/

Silverlight 2.0 - more to come

So this is just killing me. So much goodness in the super secret builds that I can't talk about that its just killing me... SOOOO just so you know as soon as it is public there will be LOTS and LOTS of stuff to post that I cant really talk about at all. In fact probably the first day I'll post probalby 50 things plus. Anyway now that 'that' is almost off my chest.

Monday, February 4, 2008

Silverlight Game

Here is a cool silverlight game Tim H. found on silverlight insiders.

http://www.miniclip.com/games/zombomatic/en/

Wednesday, January 30, 2008

Anatomy of a Silverlight Animation

For the most part we should be using Storyboards to do animations. Though it is possible to do programmatic animation and we do sometimes programmatically set properties the Storyboard infrastructure in Silverlight provides a standard easy to use and optimized way to-do animation and is a key tenet of the Silverlight technology especially around performance.

Storyboards like other elements in Xaml are defined with tags. The Storyboard element then can be a resource or in a trigger. We can also point a Storyboard at a specific element where each animation can target a different property and we can also target each specific animation at a given element and property separately. Let us start with a Storyboard then like this example:

<Storyboard x:Name="MyFirstStoryBoard"></Storyboard>

From this Storyboard we will build out our animations. The individual animations go in the story board. There are several kinds of animations such as color, point, key frame and key spline animations but we will start with point and color animations. Now look at this simple double animation.

<DoubleAnimation Storyboard.TargetName="PolygonElement"
Storyboard.TargetProperty="(Canvas.Left)"
To="48" Duration="0:0:3" />

This is a DoubleAnimation that, when the Storyboard is triggers changes one property value to another over the course of the duration. In this case the animation is targeted on the PolygonElement at the Left value. This animation does not have a ‘From’ setting so the property goes from whatever value it at to the ‘To’ setting and then over the duration of the ‘Duration’ setting in this case 3 seconds. We could also set a ‘BeginTime’ using the same time format as that of the Duration like this code sample:

<DoubleAnimation Storyboard.TargetName="PolygonElement"
Storyboard.TargetProperty="(Canvas.Left)" From="5"
To="48" Duration="0:0:3" BeginTime="00:00:02" />

This animation then targets the Canvas.Left property of the element named ‘PolygonElement’. At 2 seconds past the trigger of the animation it will change the left value from 5 to 48 over the course of 3 seconds. This was a double animation and you can have any number of these in a given story board. You can also use color animations in the same way with double animations. Take this code example:


<ColorAnimation
Storyboard.TargetName="PolygonElement"
Storyboard.TargetProperty="(Fill).(Color)"
From="#3c5f0c" To="#728f4a" Duration="0:0:5" />

Like the double animation earlier this ‘ColorAnimation’ is targeted at the same element but on a different property namely one that is a color ‘Fill.Color’. When this animation is triggered the ‘Fill.Color starts at one color and transforms to the other over the course of 5 seconds.

Tuesday, January 29, 2008

Silverlight Applications Taking All the Available Realestate

Karim sent me this. It is a simple way make sure you Silverlight Application uses all the available realestate using just CSS:


/* hide from ie on mac \*/
html
{
height: 100%;
overflow: hidden;
}
.silverlightHost
{
height: 100%;
width: 100%;
}
/* end hide */

body
{
height: 100%;
margin-left: 1px;
margin-top: 1px;
margin-right: 0px;
margin-bottom: 0px;
padding: 0;
}


Now there are other ways todo this such as from the HTML body onload event and also the resize event on the window together or other programatic ways but this is just nice and simple and I say keep it simple unless you have to.

Lunch at MIX

Anyone going to MIX that wants todo lunch let me know... I know at MIX there will be alot of 'new' stuff and I will probably have 1000 posts on SL 2.0 at MIX... all stuff that is super secret now...