Overlapping TabItems with the Silverlight Toolkit TabControl

OverlappingTabs

Standard TabItems are not overlapping, but designers like them to. You may encounter a design with overlapping tabs that you have to create and implement. This is not a simple task, certainly when the tabs have a tapered side that overlaps the tab to the right of it. The Z-Index of these tabs are opposite to the standard layout.

Control Vendors have custom versions of a TabControl, that use properties for overlap. The Toolkit TabControl currently doesn’t support overlapping tabs, but by updating templates and a bit of C# code you can get the same effect. Here’s how it’s done:

Creating an overlapping tab in Expression Design:

OverlappingTabsCreate01

  1. Start Design, start a new file with a size of 640 x 480 pixels.
  2. Add a rectangle, 50 pixels wide, 25 pixels high and make its CornerRadius 3 pixels. Make sure the Rectangle is selected.
  3. Choose Object. Convert Object to Path. This way you can change the vertices of the shape.
  4. Select the Direct Selection tool (second from the top in the Toolbox) and select the bottom right two vertices by dragging a selection area around them.
  5. Drag the two vertices to the right, about half the width of the rectangle. Hold the Shift key to constrain the translation horizontally.
  6. Zoom in to the right hand side of the shape. With the Pen Tool selected, at the right bottom corner delete the second vertice from the bottom by clicking on it.
  7. Hold the Alt Key and click the other vertice to make it a rounded point (fig. 1).
  8. Select the Direct Select Tool and move the second vertice from the top to the right. Select the Pen Tool, hold the Alt Key and drag from this anchor point in the direction of the line of the tab, so the sharp corner becomes smooth.
  9. Using the Direct Selection Tool, move the left vertice at the left bottom corner down to the bottom of the tab, delete the other by clicking on it with the Pen Tool selected (fig. 3).

OverlappingTabsCreate02

figure 1: Create a round point at the bottom right corner.

OverlappingTabsCreate03

figure 2: Create a smooth corner at the top right corner.

OverlappingTabsCreate04

figure 3: Remove a anchor point to create a straight corner at the lower left corner.

Double click the Magnifying Glass Icon at the bottom of the toolbox to show the entire drawing. It helps to place the top right corner of the tab at the 0,0 coordinates using the Action Bar at the bottom of the screen. Check if the Foreground color is white and the border is black. Make sure the tab is selected, showing its bounding box and transformation handles, and select Edit, Copy from the menu.

Implementing overlapping tabs in Expression Blend:

  1. Start Blend, Begin a new Silverlight project, Open MainPage.xaml.
  2. Open the Asset Panel, enter Tab in the search box, select TabControl and drag a rectangle on the Artboard. You’ll get a TabControl with two tabs. A reference to System.Windows.Controls.dll is added to the project references and a namespace xmlns:controls is added to your MainPage.xaml file.
  3. The TabControl is a container for the TabItems. It has a four Grids to place tabs on all sides of the tab area. Tabitems are placed in these grids. The TabItems consist of a Header and a Grid as you can see in the Object and Timeline Panel when a tab is selected. Right click a Tab and select Edit Template, Edit a Copy… from the context menu, choose a name and a location for the ControlTemplate and click OK.

OverlappingTabsImplement01

figure 4. Creating a TabItem ControlTemplate

  1. You’ll enter Template Editing Mode for the TabItem. The Objects and Timeline panel shows eight grids and a FocusVisualElement Border. For each of the four sides (Top, Bottom, Left, Right) you’ll see a Selected and a Unselected Part. Control Parts are recognizable by the green icon next to their name. You can also find them in the Parts Panel.
  2. Locate the TemplateTopSelected Grid in the Object and Timeline Panel and open all the borders and grids that are part of it by clicking the small triangles in from of it. Drag the ContentControl named HeaderTopSelected up to the TemplateTopSelected Grid so it moves to the same hierarchical level. Now you can delete the rest of the content of the TemplateTopSelected Grid. Also delete all the animations that reference those shapes if they are not deleted by Blend.
  3. With this Grid selected, choose Paste from the edit menu. This will place the tab you created in Expression Design into the grid. Remove its Margins to make the tab fit inside the Grid.
  4. Drag the layer of the new Path up so it is placed right beneath the TemplateTopSelected Grid and above the Focus and Disabled visuals in the Objects and Timeline Panel. Move the HeaderTopSelected Content Control beneath the Path.
  5. Repeat Step 3 and 4 for the TemplateTopUnselected Grid. Make its Foreground a slightly darker color than the selected state of the tab.
  6. Set for both the TemplateTopSelected as the TemplateTopUnselected Grid the left margin to –20 pixels. This will ruin the bounding box placing in Blend, but move the tabs to the left at runtime.
  7. Make sure the Grid for the selected state of the tab has a Path at the bottom, that makes the connection with the tab area beneath it. It is important that a tab connects to the area that shows when a tab is selected.
  8. You may want to delete the FocusVisualTop border because it is rectangular and your tabs are not. Also remove any animations targeting this control.
  9. Scope up to the Control Level using the breadcrumbs at the top of the screen or the Return Scope to [UserControl] button at the top of the Objects and Timeline Panel.
  10. Right Click the TabControl and Select Edit Additional Templates, Edit Layout of Items [ItemPanel], Create New. Make sure it is a StackPanel with its Orientation set to Horizontal. Scope up to the Control Level.
  11. Right Click the TabControl (not a tab) and Select Edit Template, Edit a Copy… Give the System_Windows_Controls_Primitives:TabPanel a left margin of 20, but leave the other margins as they are: margin=”20,2,2,-1″ compensating for the negative left margin on the first TabItem.
  12. Use the Visual State Manager to create a state for a MouseOver that is a light gray between the selected and unselected Foreground colors. A transition time of half a second gives the right effect.

        <controls:TabControl x:Name=”TabControl” Width=”500″ Height=”100″
             Style=”{StaticResource TabControlStyle1}”
             ItemsPanel=”{StaticResource ItemsPanelTemplate1}”
             SelectionChanged=”TabControl_SelectionChanged”>
            <controls:TabItem x:Name=”Tab_1″ Header=”Tab 1″
                 Style=”{StaticResource TabItemStyle1}”>
                <Grid Background=”#FFE5E5E5″>
                    <TextBlock Text=”Area 1″ Margin=”20″/>
                </Grid>
            </controls:TabItem>
            <controls:TabItem x:Name=”Tab_2″ Header=”Tab 2″ 
                Style=”{StaticResource TabItemStyle1}”> 
                <Grid Background=”#FFE5E5E5″>
                    <TextBlock Text=”Area 2″ Margin=”20″/>
                </Grid>
            </controls:TabItem>
            <controls:TabItem x:Name=”Tab_3″ Header=”Tab 3″
                 Style=”{StaticResource TabItemStyle1}”>
                 <Grid Background=”#FFE5E5E5″>
                      <TextBlock Text=”Area 3″ Margin=”20″/>
                 </Grid>
            </controls:TabItem>
            <controls:TabItem x:Name=”Tab_4″ Header=”Tab 4″
                 Style=”{StaticResource TabItemStyle1}”>
                 <Grid Background=”#FFE5E5E5″>
                     <TextBlock Text=”Area 4″ Margin=”20″/>
                 </Grid>
            </controls:TabItem>
        </controls:TabControl>

Getting the ZIndex right

All this will create the right shape and states of the the TabControl, but the order of the tabs is still wrong. By default the first tab is selected and a right tab will overlap a left tab. With overlapping tabs this should be the other way around. Setting the Canvas.ZIndex property of the TabItems in XAML won’t help. The control is initialized with the wrong settings at runtime.

A little C# helps. Thanks to Rachel, who solved this problem in WPF, we can set the overlapping tabs in the right order when the SelectionChanged event of the TabControl is fired:

private void TabControl_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)

    TabControl tabControl = sender as TabControl; 
    tabControl.Dispatcher.BeginInvoke( new Action(() =>
            UpdateZIndex(sender as TabControl)));
}

private void UpdateZIndex(TabControl tc)

    if (tc != null)
    {
        foreach (TabItem tabItem in tc.Items)
        {
            tabItem.SetValue(
                        Canvas.ZIndexProperty,
                        (tabItem == tc.SelectedItem ?
                        tc.Items.Count :
                        (tc.Items.Count-1) – tc.Items.IndexOf(tabItem)));
        }
    }
}

The UpdateZIndex method is invoked in a way that updates all the TabItems. This way a left tab will show above a right tab the way you want in overlapping TabItems.

OverlappingTabs

fig 5. Overlapping tabs have a reversed ZIndex.

Working code is at my SkyDrive

Joe Gershgorin has refactored the code to use a Behavior. This also supp0rts longer text in the headers. You can find his version at: http://www.bitspy.com/OverlappingTabs_Silverlight4.zip

Njoy!

QuoteFloat: Animating TextBlock PlaneProjections for a spiraling effect in Silverlight

[silverlight: http://members.chello.nl/s.dol/QuoteFloat.html]

QuoteFloat is an animation for TextBlock elements, inspired by the way the HTC Touch HD shows SMS Text messages. It moves the text up and rotates it at the same time resulting in a spiraling effect. It is done by giving the TextBlock elements a PlaneProjection each and animating the RotationY and GlobalOffsetY properties.

The TextBlock elements are positioned below the bottom of the Canvas. The Canvas has a Clipping Mask so no one will see them until the animation starts. The XAML looks like this:

[sourcecode language=”XML”]
<Canvas x:Name="cvsBg" Width="500" Height="155"
Clip="M0.5,0.5 L499.5,0.5 L499.5,154.5 L0.5,154.5 z">
<TextBlock x:Name="txt1" Text="Txt1" Canvas.Top="192"
Style="{StaticResource TextBlockStyle1}">
<TextBlock.Projection><PlaneProjection/></TextBlock.Projection>
</TextBlock>
    <TextBlock x:Name="txt2" Text="Txt2" Canvas.Top="228"
     Style="{StaticResource TextBlockStyle1}">
     <TextBlock.Projection><PlaneProjection/></TextBlock.Projection>
</TextBlock>
    <TextBlock x:Name="txt3" Text="Txt3" Canvas.Top="265"
    Style="{StaticResource TextBlockStyle2}">
    <TextBlock.Projection><PlaneProjection/></TextBlock.Projection>
    </TextBlock>
</Canvas>
[/sourcecode]

I use two Styles for the two TextBlocks. Notice the second style is BasedOn, so it needs only to define the properties that are different from the first style. The Canvas.Top property is different for all the TextBlocks and defined inline in the XAML above.

[sourcecode language=”XML”]
<Style x:Key="TextBlockStyle1" TargetType="TextBlock">
    <Setter Property="Foreground" Value="White"/>
    <Setter Property="Width" Value="400"/>
    <Setter Property="Height" Value="25"/>
    <Setter Property="FontSize" Value="21.333"/>
    <Setter Property="FontFamily" Value="Trebuchet MS"/>
    <Setter Property="TextAlignment" Value="Center"/>
    <Setter Property="Canvas.Left" Value="50"/>
</Style>
<Style x:Key="TextBlockStyle2" TargetType="TextBlock"
    BasedOn="{StaticResource TextBlockStyle1}">
    <Setter Property="FontSize" Value="14"/>
    <Setter Property="Canvas.Left" Value="200"/>
</Style>
[/sourcecode]

The actual animations are quite repetative, being almost the same for all TextBlock elements. The crucial word here is almost: the animations differ for .2 seconds. Stopping the text is the natural result from easing out and the easing in the animation.

QuoteFloatStoryboard

[sourcecode language=”XML”]<Storyboard x:Name="QuoteFloat" RepeatBehavior="Forever">
    <DoubleAnimationUsingKeyFrames
        BeginTime="00:00:00" Storyboard.TargetName="txt1"
        Storyboard.TargetProperty=
            "(UIElement.Projection).(PlaneProjection.RotationY)">
        <EasingDoubleKeyFrame KeyTime="00:00:00" Value="90"/>
        <EasingDoubleKeyFrame KeyTime="00:00:01.5" Value="0">
            <EasingDoubleKeyFrame.EasingFunction>
                <CubicEase EasingMode="EaseOut"/>
            </EasingDoubleKeyFrame.EasingFunction>
        </EasingDoubleKeyFrame>
        <EasingDoubleKeyFrame KeyTime="00:00:03" Value="-90">
            <EasingDoubleKeyFrame.EasingFunction>
                <CubicEase EasingMode="EaseIn"/>
            </EasingDoubleKeyFrame.EasingFunction>
        </EasingDoubleKeyFrame>
… more animations

    <DoubleAnimationUsingKeyFrames
        BeginTime="00:00:00"
        Storyboard.TargetName="txt2"
        Storyboard.TargetProperty=
            "(UIElement.Projection).(PlaneProjection.RotationY)">
        <EasingDoubleKeyFrame KeyTime="00:00:00.2" Value="90"/>
        <EasingDoubleKeyFrame KeyTime="00:00:01.7" Value="0">
            <EasingDoubleKeyFrame.EasingFunction>
                <CubicEase EasingMode="EaseOut"/>
            </EasingDoubleKeyFrame.EasingFunction>
        </EasingDoubleKeyFrame>
        <EasingDoubleKeyFrame KeyTime="00:00:03.2" Value="-90">
            <EasingDoubleKeyFrame.EasingFunction>
                <CubicEase EasingMode="EaseIn"/>
            </EasingDoubleKeyFrame.EasingFunction>
        </EasingDoubleKeyFrame>
… more animations

[/sourcecode]

The text was not set using code, but in Blend. It then uses a DiscreteObjectKeyFrame for the TextBlock Text property and uses the given String Value.

[sourcecode language=”XML”]
   <ObjectAnimationUsingKeyFrames
BeginTime="00:00:00"
Storyboard.TargetName="txt1"
Storyboard.TargetProperty="(TextBlock.Text)">
     <DiscreteObjectKeyFrame KeyTime="00:00:00" Value="Technology requires design"/>
     <DiscreteObjectKeyFrame KeyTime="00:00:03" Value="Imagine users as very intelligent"/>
     <DiscreteObjectKeyFrame KeyTime="00:00:06" Value="No matter how cool you interface is,"/>
     <DiscreteObjectKeyFrame KeyTime="00:00:09" Value="Significant change"/>
   </ObjectAnimationUsingKeyFrames>
[/sourcecode]

The Loaded event of the UserControl is used to start the animation in the MainPage CodeBehind file:

[sourcecode language=”XML”]
<UserControl x:Class="QuoteFloat.MainPage"
    xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
    xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
    Width="500" Height="155" Loaded="StartAnim">
[/sourcecode]

 

[sourcecode language=”XML”]

private void StartAnim(object sender, System.Windows.RoutedEventArgs e)
{
    QuoteFloat.Begin();
}

[/sourcecode]

Complete Blend project is on my SkyDrive…

Njoy!

Silverlight Togglebutton Push Pin Style with IsoStore

Now you can pin a full-screen app to a second monitor in Silverlight 4, you may want an UI control to facilitate this. In fact, what you need is a ToggleButton. And your ToggleButton has to be communicate it’s function. A Push Pin Style is a good solution for that.

This Push Pin Style for a silverlight (or WPF) ToggleButton is small, totally customizable and free :). It features tooltips to show the action you can do. The setting is stored in IsoStore and picked up the next time you start your app. The states are each represented using a canvas, so you can easily swap the visuals for your own if you want to.

PushPin

The XAML is simple:

<ToggleButton x:Name="btnPin" Style="{StaticResource btnPin}" Checked="pin" Unchecked="unpin" Content="" ToolTipService.ToolTip="Pin this"/>

Files are too large to include here, but I put the project on my SkyDrive.

Njoy!

Accessing Properties and Objects in Silverlight Datatemplates using Loaded and FindName

Accessing properties and objects in a DataTemplate is not as easy as you would think. Normally the Template is separated from the item that uses it. You can find the DataTemplate as a Resource, but you cannot use the VisualTreehelper on it.

DataTemplate dt = Application.Current.Resources[“TheDataTemplate”] as DataTemplate;
int count = VisualTreeHelper.GetChildrenCount(dt);

This leads to the error: Reference is not a valid visual DependencyObject.

The solution is to use the Loaded event of the outermost container, quite often a Grid and use FindName in the EventHandler to get to Objects inside the DataTemplate and to properties of those:

<DataTemplate x:Key=”TheDataTemplate”>
    <Grid x:Name=”TheGrid” Grid.Row=”0″ Loaded=”TheGrid_Loaded”>
        //Objects and properties are here…
    </Grid>
</DataTemplate>

//enabling buttons in DataTemplate when Oob en Elevated…
private void TheGrid_Loaded(object sender, RoutedEventArgs e)
{
    if (Application.Current.IsRunningOutOfBrowser)
    {
        if (Application.Current.HasElevatedPermissions)
        {
            Grid grd = sender as Grid;

            if (grd != null)
            {
                Button c = grd.FindName(“btnCall”) as Button;
                c.IsEnabled = true;
                Button m = grd.FindName(“btnMail”) as Button;
                m.IsEnabled = true;
                Button p = grd.FindName(“btnCopy”) as Button;
                p.IsEnabled = true;
                Button v = grd.FindName(“btnVCard”) as Button;
                v.IsEnabled = true;

            }
        }
    }
}

Hope this helps! Njoy!

Silverlight Style: GlassBorderStyle

GlassBorderStyleCreated a simple, but nice Glass Border for a panel in my current Silverlight 3 project. I’d like to share it with you…

 

 

 

 

 

  <Style x:Key="GlassBorderStyle" TargetType="Border">
    <Setter Property="BorderThickness" Value="2"/>
    <Setter Property="Padding" Value="5"/>
    <Setter Property="Background">
        <Setter.Value>
            <LinearGradientBrush EndPoint="0.75,1" StartPoint="0.25,0">
                <GradientStop Color="#33FFFFFF" Offset="0"/>
                <GradientStop Color="#C0FFFFFF" Offset="0.287"/>
                <GradientStop Color="#4011322D" Offset="0.683"/>
                <GradientStop Color="#33FFFFFF" Offset="1"/>
            </LinearGradientBrush>
        </Setter.Value>
    </Setter>
    <Setter Property="BorderBrush">
        <Setter.Value>
            <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                <GradientStop Color="#5811322D" Offset="0"/>
                <GradientStop Color="#3EFFFFFF" Offset="0.25"/>
                <GradientStop Color="#FFFFFFFF" Offset="0.5"/>
                <GradientStop Color="#3EFFFFFF" Offset="0.75"/>
                <GradientStop Color="#BFFFFFFF" Offset="1"/>
            </LinearGradientBrush>
        </Setter.Value>
    </Setter>
    <Setter Property="Effect">
        <Setter.Value>
            <DropShadowEffect BlurRadius="3" ShadowDepth="3" Opacity="0.5"/>
        </Setter.Value>
    </Setter>
</Style>

To use this style:

<Border x:Name="GlassBorder" Height="100" Width="100" CornerRadius="10"
    Style="{StaticResource GlassBorderStyle}">
    <Button Content="OK"/>
</Border>

Njoy!

Use initParams to swap ResourceDictionaries and load a Theme in Silverlight 3

I’ve been looking for a way the use themes just swapping ResourceDictionaries (RD’s) for some time. Now, with Silverlight 3 being able to use MergedDictionaries, this becomes possible.

It is Blendable, but you can only use RD’s with Build Action Resource and not Content. This is annoying enough to give it another go another time. You can use the workaround of using a the RD’s with build action as Resource for use with Blend only. You’ll have to change it back before you distribute your app. Want you ultimately want is to address the RD’s as Resource…

This method can help you when you:

  • want to load a theme once on application startup
  • want to set the theme as an initParam on the Silverlight plug-in
  • don’t want to use implicit styling: you’ll need two or more RD’s with identically named Styles and Resources

Restrictions of this method are:

  • Blendable using workarounds
  • You have to use one Default theme (which can have any name you want).
  • You cannot dynamically update the theme: you can set a certain theme only once at application startup.

If this is the method for you, this is what you need to do:

  • Create ResourceDictionaries for the Default theme and for one or more other themes that you want to load in the root of your Silverlight project.
  • Use x:Keys for Styles and Resources and keep them the same between RD’s.
  • Set the Build Action for these RD’s to CONTENT in Visual Studio or by editing your .CSPROJ file by hand.
  • Insert an initParam in the <Object> tag in your startup file like this:

[sourcecode language=”XML”]

<param name="initParams" value="Theme=TheTheme" />
[/sourcecode]

  • Add a Default MergedDictionary in App.xaml:

[sourcecode language=”XML”]

<Application.Resources> 
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Default.xaml"/>
        </ResourceDictionary.MergedDictionaries>

[/sourcecode]

  • Declare a private currentTheme variable in App.xaml.cs

[sourcecode language=”XML”]

public partial class App : Application
{
    private string currentTheme = "Default";
    …

[/sourcecode]

  • Set the Default theme, get the initParam, make an URL to the filename and create and RD from that. Then add the RD to the MergedDictionaries:

[sourcecode language=”XML”]

private void Application_Startup(object sender, StartupEventArgs e)
{

    //set the current theme to the currentTheme variable
    string currentThemeName = string.Format("{0}.xaml", currentTheme);

    //get the theme name from the initParam
    string themeParameter = e.InitParams["Theme"];

    if (!string.IsNullOrEmpty(currentThemeName))
    { 
        //set the current theme to the theme parameter and create filename
        currentThemeName = string.Format("{0}.xaml", themeParameter);

        //create an URL from the currentThemeName
        Uri themeUrl = new Uri(currentThemeName, UriKind.RelativeOrAbsolute);

        try
        {
            //create a RD and set the source to the URL
            ResourceDictionary themeDictionary = new ResourceDictionary
            {
                Source = themeUrl
            };

            //Add the RD as a MergedDictionary
            Application.Current.Resources.MergedDictionaries.Add(themeDictionary);
        }
        catch (Exception ex)
        { 
            //communicate theme doesn’t exist
            throw; 
        } 
    }

    this.RootVisual = new MainPage();

}

[/sourcecode]

Many thanks to Tony Tromp and Michaud Venant for helping me out with the code.

The error “Error HRESULT E_FAIL has been returned from a call to a COM component” occurs when you forgot to change the build properties of the ResourceDictionaries to CONTENT. You can do this in Visual Studio in de Solution Explorer with the properties of the specific XAML files. This error also occurs when you maken a mistake in the name of the Theme in the initParam by messing up the quotes for example.

When you make a mistake in the Styles or the Resources used by the Styles you’ll get another error: Cannot find a Resource with the Name/Key AppBg [Line: y Position: x]. Actually if the style is OK in the Default theme it wil show that. Happily this error is easier to track and to fix, but a small error in your RD’s may have unpredictable results, so make sure they are sound.

I’ve been working with Themes from initParams for weeks. You can use Blend when you set the build action in VS to RESOURCE and restart Blend. Blend should show all the RD’s as Resources in the Resources Panel and you can edit them in the Blend artboard. You can even build in Blend and change the Theme using the initParam in the startup file. Make sure the startupfiles are the same in VS and Blend :). Before you deliver your project make sure you set the build action back to CONTENT in VS to make the theme system from initParams kick in.

I’ve placed working code on my SkyDrive.

Njoy!

10 Silverlight loading animations using percentages (HBSL3 Addendum 1)

I’ve been thinking about what ways you’d have to show a loading animation using the progress percentage in a meaningful way.

Following Mike Taulty’s rant avoiding the “Blue Balls” when loading a Silverlight application, I’ve been thinking about what ways you’d have to show a loading animation (a.k.a. Splash Screen 🙂 using the progress percentage in a meaningful way.

The idea was to come up with 10 way to do this and it proved to be harder than I thought. I’ve made a little sketch that is a little further down this post, but first let’s have a look at how to show this. Actually is it XAML only, because the application is not loaded yet, so it can only use Javascript code behind. Creating a XAML-file and a JS-file in your Web project is enough.

Create a new XAML file called SplashScreen.xaml without code behind and a Grid or Canvas as the outer container. Place a Textbox to show a percentage and some Rectangles to show the progress.

[sourcecode language=”XML”]
<Canvas
    xmlns="<a href="http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;">http://schemas.microsoft.com/winfx/2006/xaml/presentation"</a>
    xmlns:x="<a href="http://schemas.microsoft.com/winfx/2006/xaml&quot;">http://schemas.microsoft.com/winfx/2006/xaml"</a>
    Width="640" Height="480" Background="White">
  <Canvas Canvas.Top="100" Canvas.Left="100" Width="440" Height="280">
    <Rectangle x:Name="rctProgressBarTrack" Width="300" Height="25" Canvas.Top="50" Canvas.Left="10" Fill="Silver" />
    <Rectangle x:Name="rctProgressBar" Width="300" Height="25" Canvas.Top="50" Canvas.Left="10" Fill="Red">
      <Rectangle.RenderTransform>
          <ScaleTransform x:Name="rctProgress" ScaleX="0" ScaleY="1"/>
      </Rectangle.RenderTransform>
    </Rectangle>
    <TextBlock x:Name="txtStatus" Height="20" Canvas.Top="55" Canvas.Left="125" Text="Loading: " TextWrapping="Wrap"/>
  </Canvas>
</Canvas>
[/sourcecode]

In your startup file in the Web project add two lines to the Silverlight plug-in:

[sourcecode language=”XML”]
<param name="splashScreenSource" value="SplashScreen.xaml"/>
<param
    name="onSourceDownloadProgressChanged" 
    value="onSourceDownloadProgressChanged" />
[/sourcecode]

Create a small SplashScreen.js file in your Web project containing only this:

[sourcecode language=”XML”]
function onSourceDownloadProgressChanged(sender, eventArgs) {
    sender.findName("txtStatus").Text =
        "Loading: " + Math.round((eventArgs.progress * 1000)) / 10 + "%";
    sender.findName("rctProgress").ScaleY = eventArgs.progress;
}
[/sourcecode]

Now copy the SplashScreen.xaml file to your Web project. If you change it later, don’t forget to copy it into your XAML project again . You may want to create something in your MainPage.xaml so there’s something to show after loading…

progress

LoadingAnimations Here are  a 10 ideas for creating interesting loading animations. Most a using the progress percentage in some way. A few are “indeterminate” so, they could run forever. Note that the last 2 are dynamic, so should update every second or so. You can use the bars to fill other paths too, like coffee cups. You may need to scale a Clipping Mask for that.

Don’t make a Splash Screen that needs it’s own loading animation 🙂

Njoy!

Change FontSize with ElementBinding

Change text size using ElementBinding between a Slider Value and and TextBlock FontSize. With a Converter and ConverterParameter you can dynamically change the size of the text. Let users control font size!

Jakob Nielsen says: “Let users control font size”. Unfortunately in Silverlight the nice features of the WPF FlowDocument control are not available (yet). You cannot use the automatic font size feature of that control in a Silverlight app. But in Silverlight 3 ElementBinding enables you to bind a value to the FontSize attribute of a TextBlock. Using a Converter with a ConverterParameter, dynamic font size becomes available:

Click for working version...

The trick is to use TextBlock controls for your text and set it’s properties in a Style, like you would normally do. This time, leave the FontSize attribute out.

<Style x:Key=”Body” TargetType=”TextBlock”>
    <Setter Property=”FontFamily” Value=”Trebuchet MS” />
    <Setter Property=”TextWrapping” Value=”Wrap” />
</Style>
<Style x:Key=”Header” TargetType=”TextBlock” BasedOn=”{StaticResource Body}”>
    <Setter Property=”FontWeight” Value=”Bold” />
</Style>
<Style x:Key=”Caption” TargetType=”TextBlock” BasedOn=”{StaticResource Body}”>
    <Setter Property=”FontStyle” Value=”Italic” />
    <Setter Property=”Foreground” Value=”Gray” />
</Style>

Create TextBlocks with these Styles and Text, but set the FontSize attribute to an ElementBinding with the Value of a small Slider.

<TextBlock x:Name=”txtHeader1″ Style=”{StaticResource Header}”  FontSize=”{Binding Value, ElementName=Slider, Converter={StaticResource FontSizeConverter}, ConverterParameter=H1}” Text=”Header 1″/>

<Slider x:Name=”Slider” Value=”10″ SmallChange=”1″ LargeChange=”12″ Minimum=”6″ Maximum=”72″ Width=”100″ />

The converter will set the FontSize for you. The ConverterParameter has string values from “H1” to “H7”, like you would use in HTML. You can set this to any string you like, but these seem to make sense…

The converter looks like this:

using System;
using System.Windows.Data;

namespace Converters
{
    public class FontSizeConverter : IValueConverter  
    {
        public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)  
        {
            double v = (double)value;

            if (parameter != null)
            {
                string fontSizeString = parameter.ToString();
                if (!string.IsNullOrEmpty(fontSizeString))
                {
                    switch(fontSizeString)
                    {
                        case “H1” :
                            value = 2.4 * v;
                        break;
                        case “H2” :
                            value = 1.8 * v;
                        break;
                        case “H3” :
                            value = 1.4 * v;
                        break;
                        case “H4” :
                            value = 1.2 * v;
                        break;
                        case “H5” :
                            value = 1 * v;
                        break;
                        case “H6” :
                            value = .8 * v;
                        break;
                        case “H7″ :
                            value = .6 * v;
                        break;
                    }
                }
            }
            value = System.Convert.ToInt32(value); // we need an integer, not double…
            return value.ToString(); // …but as a string
        }
    }
}

As you can see the value is updated with different multipliers, depending on the header parameter you pass in. H5 is the basic text size, used by the Body Text, so its multiplier is 1. You can play with these multipliers if you want a different effect.

Add the namespace to your XAML file and put the converter as a resource at the top of the file…

<UserControl x:Class=”ControlFontSize.MainPage”
    xmlns:cvs=”clr-namespace:Converters”>
    <UserControl.Resources>
        <cvs:FontSizeConverter x:Key=”FontSizeConverter” />
    </UserControl.Resources>

… and you’re good to go. Let users control text size!

Working code is on my SkyDrive… Njoy!

Handboek Silverlight 3!

Het Handboek Silverlight 3 is uit. Het eerste en vooralsnog enige boek over Silverlight 3 in het Nederlands.

9789059403888klein_thumb.jpgEind augustus is het Handboek Silverlight 3 uitgebracht. Het eerste en vooralsnog enige boek over Silverlight 3 in het Nederlands.

Silverlight is de spannende, nieuwe techniek om met behulp van vectorafbeeldingen websites en -applicaties te creëren. Hierdoor worden visuele elementen haarscherp getoond en zijn ze schaalbaar, terwijl het downloaden sneller gaat dan bij bitmapafbeeldingen. De capaciteiten voor transparantie, kleurverlopen, animatie en 3D-projectie bieden u de kans om indrukwekkende ontwerpen te realiseren.

Wilt u een Silverlight-project van begin tot eind doorlopen, dan is dit boek voor u. Vier fasen in het proces van het creëren van een Silverlight-applicatie komen uitgebreid aan de orde:

  • Ontwerpen: over creativiteit, concept, schetsen en de gereedschappen SketchFlow en Expression Design.
  • Produceren: over XAML en de gereedschappen Expression Blend, Expression Encoder en Deep Zoom.
  • Programmeren: over de programmeeromgeving Visual Studio, aangevuld met een aantal praktische toepassingen in C#.
  • Publiceren: over het online brengen van Silverlight-sites en -applicaties, waaronder zoekmachineoptimalisatie, aangepaste installatie en uitrol in een zakelijke omgeving.

Webdesigners leren werken met eXtensible Application Markup Language (XAML), programmeurs leren hoe Silverlight aansluit op C# en het .NET-platform en ontwerpers leren hoe de grafische gereedschappen voor Silverlight precies werken. Dit boek bevat talloze bruikbare oplossingen voor problemen die u bij uw Silverlight-projecten tegen kunt komen.

Microsoft staat pal achter deze techniek en neemt het op in eigen websites, nieuwe platformen en toekomstige ontwikkelingen. Silverlight kunt u in de browser draaien, op de desktop installeren en het is onderdeel van de komende versie van SharePoint. De markuptaal XAML is niet alleen onderdeel van Silverlight, maar ook van Windows Presentation Foundation voor Windows-applicaties en van Microsoft Surface, de multi-touch tafelcomputer. Uw kennis van XAML kunt u op deze platformen ook toepassen.

Bestel ‘m alvast bij je favoriete boekhandel online:

http://www.boox.nl/nl/boek-handboek-silverlight-3-9789059403888

http://www.comcol.nl/detail/67156.htm

http://www.bol.com/nl/p/boeken/handboek-silverlight-3/1001004006437928/index.html

http://www.bruna.nl/boeken/handboek-silverlight-3-9789059403888

http://www.computerboek.nl/boek/9789059403888/handboek_silverlight_3_antoni_dol

http://www.proxis.nl/BENL/Product/Silverlight_3__Handboek/3472212__detail.aspx

Meer informatie vindt je bij de uitgever, Van Duuren Media.

How to place a vector illustration in Silverlight 2 Application Resources

Place large pieces of XAML in the application resources with the use of a Content Control and it’s Template property. Now you can place those large vector illustrations away from you page layout.

Recently, I did a presentation on how to structure a Silverlight Application using Styles and Resources. This covered several topics about structuring XAML using only the Blend User Interface as a tool.

When you create a Style, Blend goes in Style Recording mode (even though there is no visual indication of that) and all properties you set in this mode are collected in your styles automatically. Just remember to begin creating a Style, you can’t convert inline properties to styles momentarily.

You can create a Resource from almost everything (although you cannot always use them as such) using the small square to the right of the input box for the property in the Property Panel. Using the Resource Panel in Blend reorganizing Resources is straightforward. You can even move User Control Resources to the application level by dragging the layer to the Application Resource Dictionary in the Resource panel.

Placing animations in App. xaml is certainly possible with the technique I mentioned earlier. You’ll have to start the animation using code.

All this helps to set up a more structured version of your Silverlight Application. But… One thing missing from this list is how to remove large vector illustrations in XAML from you pages and place them as a resource in the application level. That way large chunks of XAML are out of the way and they can be reused using only one line of code: efficient and good for your application’s performance. With the following technique, you can put ANY large, coherent piece of XAML away as a resource. Anything that you can stash in a Grid panel, for example.

The trick is the use of a Content Control and to set it’s Template property to a ControlTemplate that is used as a Resource:

[sourcecode language=”XML”]

 

     
           
               
                   
                   
               

               
                   
                       
                           
                               
                               
                               
                               
                           

                           
                               
                                   
                               

                           

                       

                   

               

               
                   
                       
                           
                               
                               
                           

                           
                               
                                   
                                   
                               

                           

                       

                   

               

           

       

[/sourcecode]

So, clean up your XAML markup. With this trick you can remove those large vector illustrations from you screen layout and place them out of the way in app.xaml.

Njoy!