How to stop a WPF Window from moving using Touch by removing the ManipulationBoundaryFeedback

When using Touch in WPF it is possible to scroll lists. It’s just that the Window is moving to give Feedback when you are reaching the end of the list. This is not always what you want. To make your application ignore this behavior you can mark the ManipulationBoundaryFeedback event handled:

<Grid :Name="LayoutRoot" 
    ManipulationBoundaryFeedback="ManipulationBoundaryFeedbackHandler">

<DataGrid
    ScrollViewer.CanContentScroll ="False"
    ScrollViewer.PanningMode="VerticalOnly"
    ScrollViewer.PanningRatio="2"
    ScrollViewer.PanningDeceleration="1000"
    ScrollViewer.VerticalScrollBarVisibility="Hidden">
        …
</DataGrid>

.. your application is here…

</Grid>

private void ManipulationBoundaryFeedbackHandler
    (object sender, ManipulationBoundaryFeedbackEventArgs e)
{
    e.Handled = true;
}

The event is bubbling only, so if you place the event handler on your LayoutRoot it should work for all lists.

Actually there is also a System settings in the Panning Tab in the Pen and Touch settings dialog. This is a setting the end users can choose.

Njoy!

Nooks and Crannies of Expression Blend: Artboard Objects List

I can’t even find this one in the Keyboard Shortcut list provided in the User Guide of Expression Blend, so I made up a name for it: The Artboard Objects List:

ArtboardObject List

Known from several drawing programs, this list shows the objects under the mouse cursor when you hold Ctrl and Click the Right Mouse Button. It highlights the currently selected object and lists all other objects overlapping each other from the topmost at the top of the list to the one at the bottom on the bottom of the list. Notice that the order of this list is opposite to the default order in de Objects and Timeline Panel (when you have not changed the order of the panel using the Sort by Z-order option at the bottom left of that panel). Actually, this order is logical for what it shows: the stack of objects in the Artboard under your mouse cursor.

Notice also the option to Pin or UnPin the Active Container. This makes is easier to insert newly created objects in a container like the RegularPolygon Shape in the Grid here inside the RadioButton…

Njoy!

Typography in Silverlight 5

Silverlight 5 is released and contains the Typography features that already existed in WPF. Designers can use these features to make beautiful typographic designs.

SilverlightTypographyThanks to the qualities of the OpenType font format, several typographic features are now available to every web designer. Combining TrueType and Postscript outlines in one format, smaller file sizes, more typographic control and allowing far more characters in a single font file have resulted in a much more versatile use of fonts. The Typography object is available to you inside a TextBlock or TextBox tag. Attributes of this object lead to various typographic results.

Inside a TextBlock or TextBox, a Run element is used that can only contain unformatted text. Properties of the Typography object are applied through this Run element. To group some of the Run elements together, use a <Span>. Both Run and Span have no inherent rendering.

One concept associated with typography is Kerning . Kerning is embedded in the selected font file and Silverlight has no influence on it other than being able to use it or not. You can set the Typography.Kerning attribute to False. The default setting is True.

Superscript and Subscript are Variants of normal characters in a font, placed on respectively a higher or lower baseline than the rest of the text. Other Variants are Normal, Titling, Inferior, Ordinal and Ruby. Note that a Superscript and a Subscript Variant needs to be present in the font file you use.

Nobody should use a smaller font size of normal Capitals when you really need SmallCaps. Spacing of SmallCaps is different and weight and proportion of the letters are adapted to their size and use. Also, for titling purposes capitals with elegant, slender stems are possible, if they are accounted for in the specified font. Setting the property Typography.CapitalSpacing=”True” is a good idea for titles or text that are in capitals, for the spacing between capitals and lowercase letters differs from the spacing between all capitals.

Ligatures are Alternates for two characters that would collide when spaced normally. In the lowercase combination of f and i for example, the point of character i interferes with the end of the stroke of the f regularly. So in the ligature this issue is solved. The same is true for ff, fl, ffi, ffl and many other character combinations. In OpenType fonts standard ligatures are enabled by default in Silverlight 5. If for some reason standard ligatures should be disabled, use the property Typography.StandardLigatures=”False”. Other reasons for ligatures are esthetic, resulting in discretionary or historic ligatures, using Typography. DiscretionaryLigatures and Typograpy.HistoricalLigatures. Ligatures must be present in the font file for you to make them visible with the Typography object.

Swashes are decorative elements of characters associated with calligraphy. Extended serifs and strokes on existing characters may be part of your OpenFont file. To enable a Swash on a character set Typography.StandardSwashes=”1”. When a standards Swash doesn’t result in an agreeable result setting Typography.ContextualSwashes=”1 for that character is also an option.

OpenType has so many positions for characters available, that Stylistic Alternative characters are at your disposal. To enable an alternative character, set the Typograhy.StylisticAlternates property. Random use of alternatives is possible when you specify Typography.ContextualAlternates=”True”, a great way to help a script font in suggesting true handwriting. A font may also contain AnnotationAlternates. These are Glyphs in circles, squares, parentheses, diamonds or rounded boxes used for annotation of images of illustrations. In code-behind this index can be set with Typography.AnnotationAlternates.

Some characters in a font may be designed to be used together, because they look better next to each other or work together somehow. These characters are combined in a stylistic set and a maximum of 20 of these sets may be set in code-behind.

Numerical features of OpenType include Typography.Fraction=”Slashed” or Typography.Fraction=”Stacked”, old style numerals with Typography.NumeralStyle=”OldStyle” inside a Run tag and Tabular or Proportional alignment with Typography.NumeralAlignment=”Tabular” and even, where available, a slashed zero using Typography.SlashedZero=”True”.

Here’s the XAML I used for the image at the beginning:


<StackPanel Background="White" Margin="0,0,0,0">
<TextBlock FontFamily="Adobe Caslon Pro" FontWeight="Normal" TextAlignment="Center" FontSize="200" Typography.StandardLigatures="True">
<Run FontStyle="Italic" Typography.StylisticAlternates="1">fi</Run>
<Run Foreground="Red" FontStyle="Italic" Typography.StylisticAlternates="1">fl</Run>
<Run FontStyle="Italic" Typography.StylisticAlternates="1">ff</Run>
</TextBlock>
<TextBlock FontFamily="Adobe Caslon Pro" FontWeight="Normal" Margin="0,-150,0,0" TextAlignment="Center" FontSize="200" Typography.StandardLigatures="True">
<Run FontWeight="Normal" Typography.StylisticAlternates="1">fi</Run>
<Run FontWeight="Normal" Typography.StylisticAlternates="1">fl</Run>
<Run FontWeight="Normal" Typography.StylisticAlternates="1">ff</Run>
</TextBlock>
<TextBlock FontFamily="Adobe Caslon Pro" FontSize="24" Margin="0,-125,0,0" TextAlignment="Center">
<Run Text="Superscript: M"/><Run Foreground="Red" Text="2" Typography.Variants="Superscript"/>
<Run Text="Subscript: H"/><Run Foreground="Red" Text="2" Typography.Variants="Subscript"/><Run Text="O"/>
<Run FontStyle="Italic" Text="Fraction: 8"/><Run Foreground="Red" FontStyle="Italic" Text="1/2" Typography.Fraction="Slashed"/><LineBreak/>
<Run Text="CAPITALS" Typography.Kerning="True"/>
<Run Text="SmallCaps" Foreground="Red" Typography.Capitals="SmallCaps"/>
<Run Text="AllSmallCaps" Typography.Capitals="AllSmallCaps"/><LineBreak/>
</TextBlock>
</StackPanel>

Also check out Silverlight 5 OpenType Support from Pete Brown at 10REM.NET.

Njoy!

Photoshop in METRO style 2: Filters

The comments on the previous post got met re-reading the existing documentation for METRO Style Apps. It appears the content of http://msdn.microsoft.com/en-us/windows/apps is quite different when you follow the HTML5/CSS/JS path from when you follow the C++/C#/VB/XAML path. Both are far from complete and one has more complete details on specific subjects than the other. For example, the part where controls are redesigned is much more complete in the XAML section, but the general UI guidelines is more complete in the HTML5 section…

Following new insights on how to design a UI for Photoshop in METRO style I set out on creating a few new screens. Naturally time constraints don’t help in investigating this interesting Style Exercise further. I would have liked to present more screens than these two, but decided to publish this result anyway to keep a conversation going.

The Filters Gallery is one of the most elaborate dialog boxes in Photoshop. It allows you to access all filters possible and determine specific settings for filters and judge the results in the dialog itself. Recreating a Metro Style version of this dialog seemed like an interesting challenge.

The idea was to try out On-Canvas controls. These are controls that are not tucked away in an app bar at the bottom of the screen or a controls area at the top of the screen. My issue with them is that they obscure the image that you are trying to edit. I think this doesn’t help in the image editing process. I decided on a Semantic Zoom as Reidar suggested in his comments. I also wanted to show the effect of a filter on the actual image on the screen.

The Filters Gallery screen show all filters in a specific group:

PhotoshopInMetroStyle06Small
Click to show a full screen image…

It has no use showing these filter effects on the actual image beneath them, because some would only show the blue sky. No effect would be visible in most cases. I opted for a small version of the current image with the filter applied in a GridView, with the title of the filter below. The title of the group is at the top of the screen. Swiping left or right or using the arrows left and right allow you to show the other groups of filters.

The Filter Detail screens will show the filter applied to the image:

PhotoshopInMetroStyle05Small
Click to show a full screen image…

Swiping would show the next filter in the group applied to the image. I’ve inversed the Overlay, this way the filter is applied to the visible part of the image and you can judge the effect of the filter correctly.

Three sliders (common to most filters in the Photoshop Filter Gallery) are show over the filtered image. They are minimalistic as they don’t show any value, but the effect of changing them should be visible immediately. An issue here is contrast: what if the image is white or black behind the Slider controls? The Check icon that is frequently used in Windows Phone and Windows 8 Metro Style apps is below the image to Apply the filter to the current image. To remove it, usually a similar Trashcan icon is used. But it is unclear as to where that icon would show up in this design.

I see how so-called On-Canvas controls can help in the design of Metro Style UI’s. In this case the image below the controls is important and should ideally be visible all the time. I like the way the filter effect is visible on the image right away and changing the setting would should the effect on the image at once. This comes closer to Direct Manipulation…

Njoy!

A Style for the Silverlight CoverFlow Control Slider

I’ve been working with the Silverlight CoverFlow Control lately and think the default Silverlight Slider at the bottom of the screen sticks out like a sore thumb:
SilverlightCoverFlowControl
So, I’ve create a new Style for the Slider, resembling the original Cover Flow slider.
CoverFlowSlider
This is a Style for a Silverlight slider control, meant to be used on a black or dark background. It has rounded sides for the Track as well as the Thumb. The Track looks like it is lower because of the inner shadow at the top. The Thumb also has a shadow, but its surface is flat. This is only the Horizontal Template, so nothing will show when it is used vertically.
The Project File is on my SkyDrive, but the Style is simple enough to reproduce it here…
De XAML is a regular Slider with a Style:
<Slider Style="{StaticResource CoverFlowSliderControl}" Maximum="100" LargeChange="10" SmallChange="1" Value="50"/>
The Track has its own style, used in the ControlTemplate later on:
<Style x:Key="CoverFlowSliderTrackStyle" TargetType="Rectangle">
 <Setter Property="RadiusY" Value="12" />
 <Setter Property="RadiusX" Value="12" />
 <Setter Property="StrokeThickness" Value="2"/>
 <Setter Property="Stroke">
 <Setter.Value>
 <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
 <GradientStop Color="#FF202020" Offset="0"/>
 <GradientStop Color="#FF404040" Offset="1"/>
 </LinearGradientBrush>
 </Setter.Value>
 </Setter>
 <Setter Property="Fill">
 <Setter.Value>
 <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
 <GradientStop Color="Black" Offset="0"/>
 <GradientStop Color="#FF202020" Offset="0.4"/>
 </LinearGradientBrush>
 </Setter.Value>
 </Setter>
 </Style>
The Thumb is no more than two rectangles, but both have their own Style:
<Style x:Key="CoverFlowSliderThumb" TargetType="Rectangle">
 <Setter Property="RadiusY" Value="10" />
 <Setter Property="RadiusX" Value="10" />
 <Setter Property="StrokeThickness" Value="2" />
 <Setter Property="Stroke" Value="#FF4B4B4B"/>
 <Setter Property="Fill">
 <Setter.Value>
 <LinearGradientBrush EndPoint="0.5,1" MappingMode="RelativeToBoundingBox" StartPoint="0.43,-0.02">
 <GradientStop Color="#FF252525" Offset="1"/>
 <GradientStop Color="#FF787878" Offset="0"/>
 <GradientStop Color="#FF424242" Offset="0.622"/>
 </LinearGradientBrush>
 </Setter.Value>
 </Setter>
 </Style>
 <Style x:Key="CoverFlowSliderThumbCover" TargetType="Rectangle">
 <Setter Property="RadiusY" Value="8" />
 <Setter Property="RadiusX" Value="8" />
 <Setter Property="StrokeThickness" Value="0" />
 <Setter Property="Fill" Value="#FF404040" />
 <Setter Property="Margin" Value="3" />
 </Style>
 <Style x:Key="ThumbStyle" TargetType="Thumb">
 <Setter Property="Margin" Value="0,2" />
 <Setter Property="Width" Value="50" />
 <Setter Property="Template">
 <Setter.Value>
 <ControlTemplate TargetType="Thumb">
 <Grid Margin="2,0">
 <Rectangle x:Name="Thumb" Style="{StaticResource CoverFlowSliderThumb}"/>
 <Rectangle x:Name="ThumbCover" Style="{StaticResource CoverFlowSliderThumbCover}"/>
 </Grid>
 </ControlTemplate>
 </Setter.Value>
 </Setter>
 <Setter Property="Effect">
 <Setter.Value>
 <DropShadowEffect Direction="360" Opacity="0.5" ShadowDepth="3"/>
 </Setter.Value>
 </Setter>
 </Style>
There are two Repeatbuttons to the left and to the right of the Thumb. They are invisible and use the same Style:
<Style x:Key="RepeatButtonStyle" TargetType="RepeatButton">
 <Setter Property="Template">
 <Setter.Value>
 <ControlTemplate TargetType="RepeatButton">
 <Grid>
 <Rectangle RadiusY="6" RadiusX="6" StrokeThickness="2" Fill="Transparent"/>
 </Grid>
 </ControlTemplate>
 </Setter.Value>
 </Setter>
 </Style>
Finally, here is the Style for the Slider Control with the ControlTemplate that uses all Styles above…
<Style x:Key="CoverFlowSliderControl" TargetType="Slider">
 <Setter Property="Height" Value="24" />
 <Setter Property="Template">
 <Setter.Value>
 <ControlTemplate TargetType="Slider">
 <Grid x:Name="HorizontalTemplate">
 <Grid.ColumnDefinitions>
 <ColumnDefinition/>
 <ColumnDefinition Width="Auto"/>
 <ColumnDefinition/>
 </Grid.ColumnDefinitions>
 <Rectangle x:Name="Track" Grid.ColumnSpan="3" Style="{StaticResource CoverFlowSliderTrackStyle}"/>
 <RepeatButton x:Name="HorizontalTrackLargeChangeDecreaseRepeatButton" Grid.Column="0" Style="{StaticResource RepeatButtonStyle}"/>
 <Thumb x:Name="HorizontalThumb" Grid.Column="1" Style="{StaticResource ThumbStyle}"/>
 <RepeatButton x:Name="HorizontalTrackLargeChangeIncreaseRepeatButton" Grid.Column="2" Style="{StaticResource RepeatButtonStyle}"/>
 </Grid>
 </ControlTemplate>
 </Setter.Value>
 </Setter>
 </Style>
The result is a Cover Flow Slider that nicely fits in with the rest of the Cover Flow Control:
CoverFlowResult
Njoy!
Check out the Comments below about why this picture is up here…
Slide the Slider
Download the source for this Slider

Nieuw leven voor Silverlight: Silverlight 5 beta in april

De beta van Silverlight 5 wordt in de lente verwacht, waarschijnlijk tijdens de MIX 2011 conferentie op 12 tot en met 14 april in Las Vegas. De definitieve versie van Silverlight 5 wordt daarop in de loop van 2011 uitgebracht.

Ook bij de komende versie van Silverlight is gekeken naar de features die het meest gevraagd zijn op silverlight.mswish.net. Daar staan Full Databinding support en 3D bovenaan in de lijst. Verschillende aangekondigde features vindt je terug in de bovenste regionen, maar ook andere handige features worden onderdeel van Silverlight 5. Nadruk ligt op verbetering en uitbreiding van de bestaande functionaliteit, maar er zijn een paar uitzonderingen: ondersteuning voor 3D bijvoorbeeld.

3D en graphics

De grootste verassing in de Keynote van Scott Guthrie op de Silverlight Firestarter Web Cast was voor mij de aankondiging van 3D voor Silverlight. In de keynote video is vanaf 50:50 tot 55:50 een indrukwekkende demo te zien van wat er mogelijk wordt met 3D in Silverlight. Of 3D op dezelfde manier gaat werken als in Windows Presentation Foundation, valt nog te bezien. Er zijn in ieder geval modellen, animated cameras, textures en bumpmapping in de Silverlight implementatie aanwezig. De performance van de demo is in indrukwekkend. Grafische verbeteringen als een 3D immediate Mode Graphics API, GPU accelerated 3D zullen daaraan bijgedragen hebben. Daarnaast zijn Fluid Layout Transitions in Silverlight 5 beschikbaar, die het animeren van onderdelen van de UI nog eenvoudiger maken.

Tekst en printen

Daarnaast krijgt Silverlight 5 serieuze typografische verbeteringen. De scherpte van de tekst wordt verbeterd, het wordt mogelijk om tekst over meerdere kolommen te laten lopen. Er wordt volledige OpenType support beloofd, waaronder de toepassing van Leading en Kerning van characters in lettertypes. Het printen van tekst in Postscript vector format maakt niet alleen haarscherpe prints mogelijk, maar zal ook meer controle bieden over wat er precies geprint wordt en niet alleen wat er in de visual tree aanwezig is.

Data en binding

Een ander opmerkelijke en nuttige feature in Silverlight 5 wordt het zetten van breakpoints in de XAML. Dit werkt hetzelfde als breakpoints in code, maar zal daadwerkelijk een XAML-bestand openen en stoppen op de regel met het breakpoint. Van daaruit is het debuggen van data binding voorhanden. In de Locals Window worden fouten in de binding en in de final source de properties met de huidige waarden daarvan zichtbaar. Dat maakt het oplossen van problemen met bindings een stuk eenvoudiger. Bindings on Style setters maken het veranderen van application resources beschikbaar, zodat het onmiddelijk veranderen van Themes eindelijk wel  kan. Voor RIA services kan data opgeslagen worden in de cloud. Custom markup extentions helpen om een MVVM patroon beter te implementeren. Implicit Data Templates zorgt voor een default uiterlijk van een bepaald datatype over de hele applicatie heen. Relative Source binding maakt WPF features voor databinding eindelijk beschikbaar in Silverlight.

Media

Hardware media decodering geeft betere video-ervaring, terwijl CPU en batterij worden ontzien. Power Management zal bij dat laatste zelfs nog meer helpen. Pitch correction voor audio en video heet in Silverlight 5 TrickPlay. Silverlight krijgt ook de functionaliteit om afstandbedieningen aan te sturen, zodat een zogenoemde “Ten feet experience” beter ondersteund kan worden vanuit een Silverlight applicatie. Ik hoop nog altijd dat MediaCenter Markup Language (MCML) wordt vervangen door XAML, maar dat is wellicht een brug te ver.  IIS Media Services 4.0 maakt smooth streaming naar WP7, maar ook de iPhone en de iPad mogelijk met betere performance en meer mogelijkheden. Het wordt bijvoorbeeld mogelijk om Azure te gebruiken voor IIS Media Services.

Silverlight 5 zal weer talloze verbeteringen hebben ten opzichte van de huidige versie. Zo komt er een 64-bit Silverlight Runtime die sneller start, beter presteert en meer mogelijkheden biedt. Een Coded UI recorder brengt testen van de userinterface binnen bereik. Out-of-Browser Silverlight applicaties kunnen meerdere subwindows hebben, die zelfs snappen naar de kanten van het scherm in Windows 7. Entreprise Policy support laat trusted applications binnen die vertrouwde omgeving uit de sandbox komen. P/invoke laat je unmanaged DLLs en Win32 APIs aanspreken voor betere integratie met het OS en met apparaten.

Als wilt kan je alles nog eens nalezen op de Future of Microsoft Silverlight site.

When dynamically creating objects in code, use Styles

When you need to create objects in code, you can actually build up the entire look and feel in code.

This results in large blocks of code that do nothing special, but set the visual properties of an object:

Grid grdNow = new Grid();

 

//create Circle

Ellipse cirNow = new Ellipse();

cirNow.Height = 25;

cirNow.Width = 25;

cirNow.VerticalAlignment = VerticalAlignment .Center;

cirNow.HorizontalAlignment = HorizontalAlignment.Center;

cirNow.Fill = new SolidColorBrush (Colors.Red);

cirNow.Margin =new Thickness(5,5,5,5);

 

//create TextBlock

TextBlock txtNow = new TextBlock();

txtNow.VerticalAlignment = VerticalAlignment.Center;

txtNow.HorizontalAlignment = HorizontalAlignment.Center;

txtNow.Foreground = new SolidColorBrush(Colors.White);

txtNow.FontWeight = FontWeights.Bold;

txtNow.FontSize = 14;

txtNow.Margin =new Thickness(0,0,0,2);

txtNow.TextWrapping = TextWrapping.NoWrap;

txtNow.Text="now";

 

//add objects to grid

grdNow.Children.Add(cirNow);

grdNow.Children.Add(txtNow);

 

The drawback of this is that it is a lot of code and hard to maintain. The looks are integrated in the code and that is not what you want.

In Silverlight and WPF there is a standard model to separate the code from the look and feel of the application you’re building. It’s called XAML.

XAML is a markup language that’s easily generated by code and easily maintained by non-programmers with tools of even by hand.

When you are creating objects on the fly you should use Styles. These determine the way the object looks. Only keep the properties necessary for dynamically placing your object on the screen in your code:

Grid grdNow = new Grid();
Ellipse cirNow = new Ellipse();
TextBlock txtNow = new TextBlock();

cirNow.Style = App.Current.Resources["NowStyle"] as Style;
txtNow.Style = App.Current.Resources["NowTextStyle"] as Style;

grdNow.Children.Add(cirNow);
grdNow.Children.Add(txtNow);

This is a lot less code. Below is the markup that you shouldn’t have to worry about when you use Styles in your C# code.

You can even just create an empty Style block in App.xaml: <Style x:Key=”NowStyle” TargetType=”Ellipse” /> and thus use it with default values.

The look of these dynamically created objects can be changed later on or even be themed using a separate ResourceDictionary. A designer can come in at any time and change these properties using a Tool like Expression Blend.

<Style x:Key="NowStyle" TargetType="Ellipse">
    <Setter Property="Height" Value="25"/>
    <Setter Property="Width" Value="25"/>
    <Setter Property="VerticalAlignment" Value="Center"/>
    <Setter Property="HorizontalAlignment" Value="Center"/>
    <Setter Property="Fill" Value="Red"/>
    <Setter Property="Margin" Value="5"/>
</Style>
<Style x:Key="NowTextStyle" TargetType="TextBlock">
    <Setter Property="VerticalAlignment" Value="Center"/>
    <Setter Property="HorizontalAlignment" Value="Center"/>
    <Setter Property="Foreground" Value="White"/>
    <Setter Property="FontWeight" Value="Bold"/>
    <Setter Property="FontSize" Value="14"/>
    <Setter Property="Margin" Value="0,0,0,2"/>
    <Setter Property="TextWrapping" Value="NoWrap"/>
    <Setter Property="Text" Value="nu"/>
</Style>

So, when you find yourself creating a lot of C# code to set the visual properties of a dynamically created objects: Stop!

Create a Style in XAML and refer to that Style instead.

Njoy!

Using Silverlight 4 StringFormat for Data Binding a TextBlock to a Slider with no decimals showing

In Silverlight 4 it is possible to use the StringFormat extention to format output from Data Binding. I was always looking for a way to remove the trailing decimals from a TextBlock that was bound to a Slider. Today I found the answer:

<TextBlock x:Name="txtWeight" Text="{Binding Value, ElementName=sldWeight, StringFormat=\{0:n0\}}"/>

This says: Use the result as a number with zero decimals.

Use StringFormat=\{0:n1\}} if you want one decimal and StringFormat=\{0:n2\}} for two decimals. You can also use StringFormat=p for Percentage, StringFormat=c for Currency…

The Designer Silverlight site has more details…

Njoy!

Create a Button Control from an Expression Design drawing

I’ve placed a PushButton Design file in the Expression Gallery. A thousand people have actually downloaded the .design file. Only one question rose, asking how to implement that drawing as a Button Control. Here are the steps to do that:

PushButton

In Design:
– Click the square on the Layer named PushButton to select all elements
– Select File/Export and in the dialog choose XAML Silverlight 4 Canvas, Leave Text Editable, set Live Effects to Convert to XAML,  call it PushButtonNormal.xaml, remember where it is located after export. Click Export All.
– Click the square on the second Layer named PushButton Pressed to select all elements
-Select File/Export and use the same settings and location. Name it PushButtonPressed.xaml. Click Export All.

In Blend:

– Start a new Blend Silverlight Application, Call it PushButtonControl
– Open MainPage.xaml in the Code Editor using View/Active Document View/XAML View.
– Create a closing the tag for the Grid Named LayoutRoot.
– Open the PushButtonNormal.xaml file in Notepad. Cut the inner Canvas named PushButton, Paste in inside the LayoutRoot Canvas and remove Width, Height and Canvas.Left and Canvas.Top.
– Open the PushButtonPressed.xaml file in Notepad. Cut the inner Canvas named PushButton_Pressed, Paste it under the PushButton Canvas and remove Width, Height and Canvas.Left and Canvas.Top.
– Resolve naming conflicts for Ellipses, you can only have objects with unique names.
– Switch to Design Vieww using View/Active Document View/Design View.
– Right Click the PushButton Layer in the Objects and Timeline Panel. Select Group into…/Grid from the context menu.
– Right Click the PushButton layer in the Objects and Timeline Panel. Select Make into Control… from the context menu.
– In the dialog select the Button control and name it PushButtonControl. Click OK.
– This will create a Button Control and open ControlTemplate Editing Mode. A ContentPresenter is added to the Button. Because the PushButton container is a Canvas you have to reposition this using the Left and Top properties.
– Click the [Button] button in de Breadcrumbs at the top left of the Artboard to go out of Template Editing Mode.
– Right Click the PushButton_Pressed layer in the Objects and Timeline Panel. Select Cut from the context menu.
– Left Click the [Grid] layer in the Objects and Timeline Panel. Select the [Grid] button in de Breadcrumbs at the top left of the Artboard to go into Template Editing Mode again.
– Right Click the [Grid] layer and select Paste from the context menu. This will place the Pressed state of the button over the Normal state. Remove the top most Ellipse. This is the transparent shadow and should not show twice. Drag the PushButton_Pressed layer up so it is above the [ContentPresenter] layer. The word Button should appear.
– Set the Opacity Property of PushButton_Pressed to Zero (0%).
– Now you should have a [Grid] with 3 layer in it: PushButton, PushButton_Pressed and [ContentPresenter]. The Normal state should be visible. The word Button should be visible in it.
– Open the States Panel (Window/States should have a check before it) and select the Pressed State. The Pressed state recording should go on, showing a red frame around the Artboard.
– Set the Opacity of PushButton_Pressed back to 100%.
– Click the Base layer at the top of the States Panel and switch between the Pressed and Base state. Make sure the Buttons overlap exactly.
– Click the [Button] button in de Breadcrumbs at the top left of the Artboard to go out of Template Editing Mode.
– Select File/Save all
– Press F5 to build the project, so you can test it.

Optimization would include replacing the Canvases with Grid containers while keeping all Ellipses in their places. This would allow for better control of button size and placement of the ContentPresenter.

Njoy!

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:

<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>

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.

<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>

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

<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

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.

   <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>

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

<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">

 


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

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:

<param name="initParams" value="Theme=TheTheme" />
  • Add a Default MergedDictionary in App.xaml:

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

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

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

  • 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:

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();

}

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)

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.

<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>

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

<param name="splashScreenSource" value="SplashScreen.xaml"/>
<param
    name="onSourceDownloadProgressChanged" 
    value="onSourceDownloadProgressChanged" />

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

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

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

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!

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

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:


<ContentControl Template="{StaticResource ctpBullet}" />

 

      <ControlTemplate x:Name="ctpBullet" TargetType="ContentControl">
            <Grid Width="12" Height="12" VerticalAlignment="Top" HorizontalAlignment="Center">
                <Grid.RowDefinitions>
                    <RowDefinition />
                    <RowDefinition />
                </Grid.RowDefinitions>
                <Ellipse x:Name="Bullet" Grid.RowSpan="2" Stretch="Fill" StrokeThickness="0.5" StrokeLineJoin="Round" Stroke="#FF870000">
                    <Ellipse.Fill>
                        <RadialGradientBrush RadiusX="0.67158" RadiusY="0.671574" Center="0.34738,0.263298" GradientOrigin="0.34738,0.263298">
                            <RadialGradientBrush.GradientStops>
                                <GradientStop Color="#FFFFFFFF" Offset="0"/>
                                <GradientStop Color="#FFFF0000" Offset="0.512712"/>
                                <GradientStop Color="#FFCF0000" Offset="0.817797"/>
                                <GradientStop Color="#FFFF0000" Offset="1"/>
                            </RadialGradientBrush.GradientStops>
                            <RadialGradientBrush.RelativeTransform>
                                <TransformGroup>
                                    <RotateTransform CenterX="0.34738" CenterY="0.263298" Angle="57.8044"/>
                                </TransformGroup>
                            </RadialGradientBrush.RelativeTransform>
                        </RadialGradientBrush>
                    </Ellipse.Fill>
                </Ellipse>
                <Path x:Name="BulletGlow" Margin="2" Stretch="Fill" Data="F1 M 23.0627,100.787C 26.3052,100.787 28.9338,103.416 28.9338,106.659C 28.9338,109.901 26.3052,106.595 23.0627,106.595C 19.8202,106.595 17.1916,109.901 17.1916,106.659C 17.1916,103.416 19.8202,100.787 23.0627,100.787 Z ">
                    <Path.Fill>
                        <RadialGradientBrush RadiusX="1.19041" RadiusY="0.858456" Center="0.332587,0.223982" GradientOrigin="0.332587,0.223982">
                            <RadialGradientBrush.GradientStops>
                                <GradientStop Color="#FFFED4D0" Offset="0"/>
                                <GradientStop Color="#FFF27037" Offset="1"/>
                            </RadialGradientBrush.GradientStops>
                            <RadialGradientBrush.RelativeTransform>
                                <TransformGroup>
                                    <SkewTransform CenterX="0.332587" CenterY="0.223982" AngleX="22.4347" AngleY="0"/>
                                    <RotateTransform CenterX="0.332587" CenterY="0.223982" Angle="71.469"/>
                                </TransformGroup>
                            </RadialGradientBrush.RelativeTransform>
                        </RadialGradientBrush>
                    </Path.Fill>
                </Path>
            </Grid>
        </ControlTemplate>

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!

Intellisense for Expression Blend 2 SP1 working again!

Tonight I found this short cryptic message by Bennage on the MSDN Code Gallery site:

Blend 2.0 SP1
bennage
Oct 1 at 4:37 PM 
FYI I was able to get the plugin working against 2.0 sp1 simply by recompiling the source against the 2.0 sp1 assemblies.

As a designer, it was a bit too short and cryptic for me. But I decided to have a go anyway. This it what I had to do do make Intellisense working again for Blend 2 SP1:

  1. Download the original BlendSense_Install.zip from the MSDN Code Gallery site:
    http://code.msdn.microsoft.com/BlendSense/Release/ProjectReleases.aspx?ReleaseId=1358
  2. Install the Addin as explained on the Homepage: http://code.msdn.microsoft.com/BlendSense
    Blend.bat, Addins folder with a DLL and the Schemas Subfolder should all be in place. If you have a failed attempt to install BlendSense for Blend 2 SP1, you’ll probably be in good shape 😉
  3. Download the Code from the MSDN Code Gallery site:
    http://code.msdn.microsoft.com/BlendSense/Release/ProjectReleases.aspx?ReleaseId=1358
  4. Upzip it to your visual studio or Blend projects directory:
    c:\users\YOU\Documents\Expression\Expression Blend Projects
  5. Start Visual Studio or Expression Blend and load the Expression.Blend.Intellisense project
  6. Open the Solution Explorer or Project tab and check the References  folder to find several dll’s that are missing or invalid, marked by a yellow exclamation mark
  7. Right-click on the References folder and select Add Reference…
    Click the Browse tab in the Add Reference dialogbox and browse to your Blend 2 SP1 location: “c:\program files\Microsoft Expression\Blend 2”
  8. Select all the DLL files that are missing by keeping the Ctrl key down while clicking the filenames. Click OK. The yellow exclamation marks in the Solution Explorer or Project tab References folder will disappear.
  9. Build the project using Build/Rebuild Solution. If all is well, the build will succeed.
  10. Check the debug folder in de Expression.Blend.Intellisense folder for a DLL called Expression.Blend.Intellisense.dll (if you made a release build you’ll find it in the Release folder of course).
  11. Copy this file to the Add-In folder in the Expression Blend program folder: “c:\program files\Microsoft Expression\Blend 2\Addins” Replace the existing file with the same name but smaller in size with this new DLL. Don’t paste it in the Blend program folder, but in de Add-in folder.
  12. Run Blend.bat from the Blend Program folder.
    This contains the command:
    start Blend.exe -addin:Addins\Expression.Blend.Intellisense.dll
  13. Blend wil start and ask you to open your last project. Open the project.
    Press F11 twice or click the XAML tab at the top right of the working area in Blend.
  14. Press Ctrl + Spacebar inside any XAML statement to find intellisense working!

Thanks bennage for the original post at: http://code.msdn.microsoft.com/BlendSense/Thread/List.aspx and of course many, many thanks to Stefan Dobrev for making it all possible at http://blogs.telerik.com/StefanDobrev/Posts/08-08-04/IntelliSense_for_Expression_Blend.aspx

Hope this helps (I know it will!) Njoy!

WPF 3D: Presentation at the Software Development Conference (3): Deepest

deepestDe derde Demo heet Deepest en gaat over interactieve schermen op driedimensionale oppervlakken. Ik spin en flip hier planes met een Registratieformulier erop. Verder schanier ik die planes opzij in twee richtingen en draai ik ze uit de hoek in beeld voor ik ze rechtzet. Ook hier is een Harmonica te zien, eigenlijk twee: een bovenin het scherm met portretjes en een rechtsonder in het scherm die afbeeldingen bevat. Die kunnen gecombineerd worden tot interessante 3D oplossingen voor master/details scenario’s. Verder toon ik hier ook kubussen met formulieren van buiten en van binnen en draai de camera om een kubus met formulieren erop.

Daarnaast zitten er nog wat verassingen in de demo’s. Linksonder in Deep klapt een Expander uit om buttons te tonen waarmee ik de Xbox doos omvorm tot boeken over WPF 3D: 3D Programming For Windows van Charles Petzold, WPF Unleashed van Adam Nathan en mijn eigen Handboek XAML, waar ook een hoofdstuk over 3D in staat.

deepmacawenergydrinkOm te bewijzen dat andere modellen dat een rechthoekige doos ook kunnen, wilde ik een blikje frisdrank tonen. En welk blikje is beter geschikt dan die van de Macaw Liquid Energy, die ook tijdens de SDC wordt uitgereikt? Het was tamelijk eenvoudig om in de 3D modelleer applicatie ZAM3D de rechter contour van het blikje te tekenen en via de lathe functie (denk draaibank) er een cylinder van te maken. De afbeelding erop is van het oorspronkelijk ontwerp voor het etiket, al aangepast is aan de nieuwe huisstijl. Via de Viewbox en Viewport eigenschappen is die op de juiste plaats gezet en een animatie, die het blikje eindeloos ronddraait, maakt het helemaal af.

Dit alles levert materiaal op voor de mensen, die de sessie op de Software Development Conference bezoeken, met voorbeelden en code om zelf in hun interfaces met 3D aan de slag te gaan. Ze krijgen een CD mee met de presentatie en de mogelijkheid om vanuit de slides deze demo’s op te starten. Verder staat op de CD alle broncode die ik het verzameld en geschreven om deze demo’s te laten werken.

De demo en de source code zijn beschikbaar via mijn public map op mijn SkyDrive:

http://cid-8073406c0ec0e68a.skydrive.live.com/browse.aspx/Public

WPF 3D presentation at Software Development Conference(2): Deeper

Last time I mentioned the first demo of my presentation at the Software Development Conference called Deep. This dealt with product presentation, using a 2D UI for a 3D scene with only one model. In this demo, called Deeper, I will show you several effects you can use for your own UIs with WPF 3D.

The second demo (Deeper) consists of several possibilities to use a series of primitive models (plane, cube, cylinder, sphere) in User Interfaces. It show the spinning, flipping and stacking of planes, cover flow, harmonicas and carousels. Cubes are rotated en cylinders viewed from the inside. It was hard to think of good usage for a sphere and at first I only could come up with the planet Earth. With HitTesting you can point at a specific location and show it on the Earth surface. Later I also created a menu with five revolving spheres. Beyond that, you can see an animated SpotLight, transform of textures via sliders and animation of a camera around a cube.

The Demo executable and the source code are available from the public folder on my SkyDrive at:
http://cid-8073406c0ec0e68a.skydrive.live.com/browse.aspx/Public.

De tweede demo ( Deeper) bestaat uit een aantal mogelijkheden om een serie primitive modellen (plane, cube, cylinder, sphere) te gebruiken in User Interfaces. Het toont het spinnen, flippen en stapelen van planes, cover flow, harmonica en carrousel. Verder worden kubussen gedraaid en een cylinder van binnen bekeken. Voor een bol kon ik eerst alleen een aarde bedenken, waar je via HitTesting een locatie op kon aanwijzen, maar later heb ik ook een menu van vijf om elkaar heen draaiende bollen gemaakt. Verder zie je hier een geanimeerd SpotLight en is het verschuiven van textures via sliders en het animeren van de camera rond een kubus te zien.

De demo en de source code zijn beschikbaar via mijn public map op mijn SkyDrive:

http://cid-8073406c0ec0e68a.skydrive.live.com/browse.aspx/Public

Njoy!

WPF 3D presentation at Software Development Conference (1): Deep

Last week Tuesday at de Software Development Conference I finally gave the presentation called Deep, Deeper, Deepest on WPF 3D I had been preparing for weeks. Even though the attendance stuck to 18 indidividuals, evaluations showed a score of 7,6 with high scores for Use of Visual Aids. I will be posting screenshots, executables and code, along with a description of the demos. This will be spread over three consecutive posts. Today is about Deep:

Deep Demo Screenshot
Deep Demo Screenshot

Some people may have seen this first demo. It is called Deep and shows a Xbox box in the middle of the window. The demo is now filled with all features of 3D Graphics: model, geometry, camera, lights and textures. I created animations for it and several elements are controlled by sliders. The intention was to show off the capability for product presentations in WPF. This demo uses a Viewport3D, a control that participates in 2D screen layout like any other, but can only contain 3D information itself. The box is rotated using the buttons and the sliders. Using the textboxes to the left, the Width, Height and Depth are changed to update the size of the box. The Sphere to the left makes rotating the box possible, with the help of Hittesting on the Sphere. Rotating the camera is achieved, using the sliders at the top right hand side of the screen. Buttons below that will animate the camera to different views. The slider at the bottom right of the screen kan dim the lights to demonstrate the difference between AmbientLight, DirectionalLight and SpotLight. URLs of textures in the textboxes at the bottom of the screen allow the textures to be changed using Data Binding.

The Demo executable and the source code are available from the public folder on my SkyDrive at:

http://cid-8073406c0ec0e68a.skydrive.live.com/browse.aspx/Public

This makes a wonderful toy, playing around with all the possibilities a single model has using a 2D interface with buttons, sliders and textboxes. It works primarily through Element Binding to Sliders and Textboxes and uses Buttons to start the animations. You can also download and use the Code from the link above.

Njoy! 

Sommige mensen hebben willicht de eerste demo al gezien. Het heet Deep en heeft een Xbox doos in het midden. Die demo is nu verder ingevuld, zodat alle onderdelen van 3D Graphics aan bod komen: model, geometry, camera, lights, textures. Daarvoor heb ik animaties gemaakt en bovendien zijn de onderdelen via sliders te besturen. De bedoeling is om de mogelijkheden voor een productpresentatie in WPF zichtbaar te maken. Deze demo maakt gebruik van een Viewport3D, een control dat gewoon in de 2D layout van een scherm meedoet, maar zelf uitsluitend 3D informatie kan bevatten. De doos is met de buttons en sliders om te draaien en met de tekstboxen links kan de Width, Height en Depth aangepast worden om een ander formaat doos te tonen. De bol links maakt het mogelijk om via HitTesting op de bol de rotatie van de box aan te sturen. De camera wordt gedraaid met de sliders rechtsboven. De knoppen eronder animeren de camera naar een bepaalde view. De sliders rechtsonder kunnen de lichten doven en zo het verschil tussen AmbientLight, DirectionalLight en SpotLight inzichtelijk maken. URLs van textures maken het mogelijk om deze snel te veranderen.

De demo en de source code zijn beschikbaar via mijn public map op mijn SkyDrive:

http://cid-8073406c0ec0e68a.skydrive.live.com/browse.aspx/Public

Dit levert erg leuk speelgoed op, waarmee je kan spelen met alle mogelijkheden die een enkel model heeft via een 2D User Interface met buttons, sliders en tekstboxen. Het werkt voornamelijk met Element Binding aan sliders en tekstboxen. Het gebruikt Buttons om de animaties te starten. De code kan je ook downloaden via de link hierboven…

Nooks and Crannies of Expression Blend – Part 1

Working in Blend for more than a year and a half now, you should think I  have seen about every screen and dialog there is. Recently I’ve been working with WPF 3D a lot and I found the Material editor in Blend… More surprisingly even was the discovery of the Grid Column en Rowdefintions Dialogs. No more struggling to set the star size of a Column exactly or in XAML. It was there all the time. I’ll keep on the look for more Nooks and Crannies of Expression Blend. If you know one, let me know…

Silverlight Animations as Application Resources in app.xaml

I like to have my animations apart from the rest of the XAML, because they can become very lengthy and are not really relevant to the functionality of the UI. It’s better to edit them separately.

The animations in Silverlight have to be started using Event Handlers in a Code Behind file in Silverlight instead of the Triggers used in WPF. The Triggers were able to connect to the target object for an animation. The Event Handlers won’t do that for you.

You’ll have to find the Animation Resource, assign it to a Storyboard object in the Code Behind file of your page and set the Target element for that Storyboard before starting the animation.

Michel Heijman helped me out with this. This is his solution:

Create a helper class that can find Resources for you (like in WPF). Save this in the root of your project and name it ResourceLocator.cs.

using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace AnimationsAsApplicationResources
{
    public static class ResourceLocator
    {
        ///

        /// Helper method for finding resources located in app.xaml
        ///

        ///         ///
        public static object FindResource(string name)
        {
            if (App.Current.Resources.Contains(name))
            {
                return App.Current.Resources[name];
            }
            else
            {
                FrameworkElement root = App.Current.RootVisual as FrameworkElement;
                return root.FindName(name);
            }
        }
    }
}

In the Code Behind of your page, add the following to access the Animation Resource, set the TargetName for it and to run the Animation:

        private void startStoryboard1(object sender, RoutedEventArgs e)
        {
            // find the storyboard with helper class:
            Storyboard Storyboard1Resource = ResourceLocator.FindResource(“Storyboard1” ) as Storyboard;
            if (Storyboard1Resource != null)
            {
                // Set target for storyboard:
                Storyboard.SetTarget(Storyboard1Resource, Rectangle1);
                // Begin storyboard:
                Storyboard1Resource.Begin();
            }
        }

Don’t forget to place your animation in app.xaml now 🙂 No need to change the app.xaml.cs file for this…

Njoy!

Silverlight 2 beta 2 dropshadows using Blends

Lacking the DropShadow BitmapEffect that is present in Windows Presentation Foundation, we cannot use BitmapEffects to create shadows for containers. This doesn’t mean no shadows are possible in Silverlight 2. In the old days of CorelDraw 5 we used so-called Blends to create shadows in vector drawings. Blends are a feature that morphs one shape to another using several steps. In these steps new shapes are created that are in-between the starting and the resulting shape. Actually I think Expression Design does Blending. Just make sure the program can guess which vertices it can map to vertices on the resulting shape. If you don´t your shapes go haywire :).

Using XAML you can emulate Blends in vector drawing programs. Below is a piece of code that mimicks Blends. Note that the Margin used is always 1 to ensure a smooth gradient. Note too, that the used color is almost transparant Black. These transparent colors add up to a nice shade of gray. If you want to have a darker shadow, just make this color darker. I have not used Resources just to keep the XAML concise, but I would make editing the Shadow color easier. Actually, you can make a UserControl like a ShadowBorder that not only allows for changing the shadow color, but also the shadow direction. Anyone who makes a user friendly control like that, please let me know…

<Grid x:Name="LayoutRoot" Background="LightYellow" >
 <Grid  Width="300" Height="200">
  <Border CornerRadius="25" Margin="1" Background="#03000000">
  <Border CornerRadius="24" Margin="1" Background="#03000000">
  <Border CornerRadius="23" Margin="1" Background="#03000000">
  <Border CornerRadius="22" Margin="1" Background="#03000000">
  <Border CornerRadius="21" Margin="1" Background="#03000000">
  <Border CornerRadius="20" Margin="1" Background="#03000000">
  <Border CornerRadius="19" Margin="1" Background="#03000000">
  <Border CornerRadius="18" Margin="1" Background="#03000000">
  <Border CornerRadius="17" Margin="1" Background="#03000000">
  <Border CornerRadius="16" Margin="1" Background="#03000000">
  <Border CornerRadius="15" Margin="1" Background="#FFFFFFFF" />
  </Border></Border></Border></Border></Border>
  </Border></Border></Border></Border></Border>
  <Grid Margin="12" VerticalAlignment="Center" HorizontalAlignment="Center" >
   <TextBlock Foreground="Silver" Text="Your content here..." />
  </Grid>
 </Grid>
</Grid>

Njoy!

Color Palettes using Color Resources in Silverlight

I’ve been asked by a client if it was possible to make color versions of a design. I told him that that was actually very easy. And it is. It is just that you have to treat your colors a little different: you’ll have to create color palettes using Color Resources. Because that worked a little different in Silverlight 2 Beta 1 than in WPF I was on the wrong foot for a long time. Finally I worked it out and here it is:

There’s only one way to specify a Color in Silverlight:

<Color x:Key="colAccent">#FF800000</Color>

and this gets underlined in Visual Studio indicating that Color cannot have direct content (meaning the color code between the <Color> and </Color> tags). You’ll have to ignore that 🙂

All other ways to specify color won’t work in Silverlight:

  <!-- Colors in Silverlight 2 beta 2:-->
        <!-- all these don't work -->
        <!--<Color x:Key="colBrightAccent" A="FF" R="00" G="00" B="00" />-->
        <!--<Color x:Key="colBrightAccent" A="#FF" R="#00" G="#00" B="#00" />-->
        <!-- <Color x:Key="colBrightAccent" A="255" R="255" G="0" B="0" />-->
        <!--<Color x:Key="colBrightAccent" scA="1" scR="0" scG="0" scB="0" />-->

Note that at least the second and the fourth are valid in WPF. The third seems to go well in Blend, but gives an error in the browser and won’t show anything: the screen remains white.

Still, this allows you to create palettes of color. Here’s one with two colors:

<Color x:Key="colAccent">#FF800000</Color>
<Color x:Key="colBrightAccent">#FFFF0000</Color>

  

You can use these in SolidColorBrushes and LinearGradienBrushes like these:

        <!-- Brushes that can apply those colors using color resources -->
        <SolidColorBrush x:Key="brAccent" Color="{StaticResource colAccent}" />
        <SolidColorBrush x:Key="brBrightAccent" Color="{StaticResource colBrightAccent}" />

        <!--Gradient Brushes can use those colors too! -->
        <LinearGradientBrush x:Key="lgbrAccent" StartPoint="0.5,0" EndPoint="0.5,1">
            <GradientStop Color="{StaticResource colBrightAccent}" Offset="0" />
            <GradientStop Color="{StaticResource colAccent}" Offset="1" />
        </LinearGradientBrush>

Place all this in app.xaml between de <Application.Resources> tags and you’ll be ready to apply them in some normal XAML:

 <Grid x:Name="LayoutRoot" Width="200" Height="150">
  <Grid.RowDefinitions>
   <RowDefinition /><RowDefinition /><RowDefinition />
  </Grid.RowDefinitions>
  <Rectangle Grid.Row="0" Fill="{StaticResource brAccent}" Stroke="{StaticResource brBrightAccent}" RadiusY="25" RadiusX="25" StrokeThickness="5"/>
  <Rectangle Grid.Row="1" Fill="{StaticResource brBrightAccent}" Stroke="{StaticResource brAccent}" RadiusY="25" RadiusX="25" StrokeThickness="5"/>
  <Rectangle Grid.Row="2" Fill="{StaticResource lgbrAccent}" Stroke="{StaticResource brAccent}" RadiusX="25" RadiusY="25" StrokeThickness="5" /> 
 </Grid>

What makes it easy to make color versions of a design is the fact that you can easily replace the two color codes in the Palette to change the look of the entire application! This would do the trick:

  <Color x:Key="colAccent">#FF008000</Color>
  <Color x:Key="colBrightAccent">#FF00FF00</Color>

Be aware of the use of a Color Resource (colBright) in a LinearGradientBrush, but a Brush Resource (brBright) when you use it for a Fill or a Stroke.

So with about 10 colors as resource in app.xaml, you can actually create a basis for skinning your application. It’s just that now I still have to replace all the separated colors in my project with StaticResources and that will take some time… So now it is easy, but it will take a while 🙂 If you remember to work like this from scratch, you’ll be fine when a client ask you if color versions are possible…

Njoy!

Using the Blend Visual State Manager (VSM) on the MediaPlayer-style VideoButton

 Last weekend I played around with the new version of Blend 2.5 to see how the Visual State Manager (VSM) was working. I was pleasantly surprised by the simplicity of it all. Actually it works just like an animation. You just don’t need a timeline for states. So if you know how to animate in Blend, it is fairly easy to add states to buttons. To show you, I’ve adde states to the MediaPlayer-style videobutton I made in the previous post.

First doubleclick the button in the Objects and Timeline category in the Interaction Panel. A yellow line indicates it is selected. Then from the Button in the breadcrumbsbar below the titel of the document, click the little arrow and select Edit ControlParts (Template) and Edit Template. Since we’re using a button with a self-made template we already have a template. If you start with a new button, you’ll have to create a template using the menu first.

In the button Template, the States Category in the Interaction Panel will show several default states for the button. Below,  I’ve selected the pressed state. The “State Recording is on” message appears in red and just like in animating, you can now change Opacity, Color for that state. You can even use transformation, as you may notice that the glow and the TextBlock are moved down a few pixels.

The Name of the elements of the button in the Templates are preceded by a red circle with a white arrow to indicate it is particitpating in the current state. I have not discovered how to delete this using the UI, but you can easily find it in the XAML is you have to.

You can add transitions for the several states of this button using the + icons and – icons on the State bars. Change the transistion time with the (as buttons disguised) TextBoxes. You can drag to change the value like in other TextBoxes in Blend.

These are the states I created: a lighter yellow for the MouseOver, a darker yellow and transitions on the glow and text for the Pressed and a colorless version for the Disabled state. Note the the Focus state kicks in when the button is Pressen and remains Focused when released…

 

 

 

 

 

 

 

 

 

 

 

 

The XAML that the VSM generates is rather lengthy. Just as an example here’s the state which has least code (except for the Normal state that has an empty Storyboard)…


       <vsm:VisualStateManager.VisualStateGroups>
        <vsm:VisualStateGroup x:Name="CommonStates">
         <vsm:VisualStateGroup.Transitions>
          <vsm:VisualTransition Duration="0:0:0.2" To="MouseOver"/>
          <vsm:VisualTransition Duration="0:0:0.1" To="Pressed"/>
         </vsm:VisualStateGroup.Transitions>

         <vsm:VisualState x:Name="Normal">
          <Storyboard/>
         </vsm:VisualState>

         <vsm:VisualState x:Name="MouseOver">
          <Storyboard>
           <ColorAnimationUsingKeyFrames Duration="0" Storyboard.TargetName="BackgroundGradient" Storyboard.TargetProperty="(Shape.Fill).(GradientBrush.GradientStops)&#91;2&#93;.(GradientStop.Color)">
            <SplineColorKeyFrame KeyTime="0" Value="#FFFFFB93"/>
           </ColorAnimationUsingKeyFrames>
           <ColorAnimationUsingKeyFrames BeginTime="00:00:00" Duration="00:00:00.0010000" Storyboard.TargetName="BackgroundGradient" Storyboard.TargetProperty="(Shape.Fill).(GradientBrush.GradientStops)&#91;0&#93;.(GradientStop.Color)">
            <SplineColorKeyFrame KeyTime="00:00:00" Value="#FFFEFF77"/>
           </ColorAnimationUsingKeyFrames>
           <ColorAnimationUsingKeyFrames BeginTime="00:00:00" Duration="00:00:00.0010000" Storyboard.TargetName="BackgroundGradient" Storyboard.TargetProperty="(Shape.Fill).(GradientBrush.GradientStops)&#91;1&#93;.(GradientStop.Color)">
            <SplineColorKeyFrame KeyTime="00:00:00" Value="#FFFDB005"/>
           </ColorAnimationUsingKeyFrames>
          </Storyboard>
         </vsm:VisualState>

        </vsm:VisualStateGroup>
       </vsm:VisualStateManager.VisualStateGroups>

Njoy!

Create a MediaPlayer11-style Playbutton with glow

Just to show how easy it is to make a button in MediaPlayer11-style. Here’s a short HowTo on how to do this in Expression Blend:

In Blend, open a New Project…

Select Ellipse in Toolbox

Drag Ellipse 150px, Hold Shift to constrain to circle

 

 

 

Click Stroke, Add 3px brown stroke to the circle

Create RadialGadient Yellow, Dark Yellow, Yellow

Click Brush Transform in Toolbox (G):

 

 

 

 

<Ellipse Stroke="#FF722400" StrokeThickness="3">
	<Ellipse.Fill>
		<RadialGradientBrush GradientOrigin="0.35,0.35">
			<RadialGradientBrush.RelativeTransform>
				<TransformGroup>
					<ScaleTransform CenterX="0.5" CenterY="0.5" ScaleX="1.5" ScaleY="1.5"/>
					<TranslateTransform X="-0.09" Y="-0.12"/>
				</TransformGroup>
			</RadialGradientBrush.RelativeTransform>
			<GradientStop Color="#FFFDFF00" Offset="0"/>
			<GradientStop Color="#FFC48700" Offset="0.75"/>
			<GradientStop Color="#FFFFDE00" Offset="1"/>
		</RadialGradientBrush>
	</Ellipse.Fill>
</Ellipse>

Copy And Paste Ellipse in front of existing Ellipse

Hold ALT and Shift dragging lowerleft handle to the middle of the ellipse.

 

 

 

Fill LinearGradient White on Top, White op bottom, with Alpha set to Zero.
Set Stroke to none

 

 

 

Select Object/Path/Convert to Path

Select Direct Selection Tool in ToolBox (A)

 

 

 

Drag bottom Controlpoint up above the middel of the lower ellipse

 

 

 

 

Finish up with characters from WingDings font and a circle with Black to White diagonal LinearGradient behind the button.

 

 

 

Njoy!


 <Grid x:Name="VideoButton" Width="200" Height="200" Background="Black">
  <Ellipse Stretch="Fill"  Width="175" Height="175">
   <Ellipse.Fill>
    <LinearGradientBrush EndPoint="1,1" StartPoint="0,0">
     <GradientStop Color="#FFFFFFFF" Offset="1"/>
     <GradientStop Color="#FF000000" Offset="0"/>
    </LinearGradientBrush>
   </Ellipse.Fill>
  </Ellipse>
  <Ellipse Stretch="Fill" Stroke="#FF000000"  Width="150" Height="150">
   <Ellipse.Fill>
    <RadialGradientBrush GradientOrigin="0.33,0.33">
     <RadialGradientBrush.RelativeTransform>
      <TransformGroup>
       <ScaleTransform CenterX="0.5" CenterY="0.5" ScaleX="1.3" ScaleY="1.3"/>
       <TranslateTransform X="-0.015" Y="-0.075"/>
      </TransformGroup>
     </RadialGradientBrush.RelativeTransform>
     <GradientStop Color="#FFFDFF00" Offset="0"/>
     <GradientStop Color="#FFC48700" Offset="0.775"/>
     <GradientStop Color="#FFFFDE00" Offset="1"/>
    </RadialGradientBrush>
   </Ellipse.Fill>
  </Ellipse>
  <TextBlock VerticalAlignment="Center" TextAlignment="Center"><Run FontFamily="Webdings" FontSize="96" Text=":"/></TextBlock>
  <Path Margin="0,-55,0,0" Width="125" Height="75" Stretch="Fill" Data="M181.5,88.5 C181.5,137.10106 139.84441,74.306452 89.862639,74.306452 39.880869,74.306452 0.5,137.10106 0.5,88.5 0.5,39.898942 41.01823,0.5 91,0.5 140.98177,0.5 181.5,39.898942 181.5,88.5 z">
   <Path.Fill>
    <LinearGradientBrush EndPoint="0,1" StartPoint="0,0">
     <GradientStop Color="#FFFFFFFF" Offset="0"/>
     <GradientStop Color="#00FFFFFF" Offset="1"/>
    </LinearGradientBrush>
   </Path.Fill>
  </Path>
 </Grid>

Visual Studio 2008 Design View uitzetten

Omdat ik toch in Blend werk en VS2008 uitsluitend gebruikt voor het Rebuilden van de Solution, heb ik de Design View niet echt nodig. Ik wissel altijd de Panels om en klik de Design View weg. Sterker nog, het stoort erorm als ik even  een XAML file wil openen in VS2008, omdat de XAML code er meteen staat, maar het programma toch de tijd neemt om de XAML te redeneren in een Design View die buiten beeld staat. Ik heb even geklaagt en daarna toch nog even beter gezocht, maar je kan de Design View toch uitzetten. De omschrijving van de optie in VS2008 is een beetje cryptisch, maar met deze afbeelding zou je het zelf moeten kunnen uitvoeren:

 Remove Design View voor XAML in Visual Studio 2008

Succes!

Kickoff: Droplet

Om mee te beginnen wil ik een projectje delen, waarin ik geprobeerd heb het logo van een interactieve TV aanbieder in XAML te bouwen. Het bleek een leuke exercitie, met een resulaat dat veel had van het origineel:

In XAML bleek een eenvoudige droplet een combinatie van twee cirkels en een ‘cashewnoot’ Path Shape voor de glimmer. Deze laatste heb ik met de hand getekend in Blend, maar ze zijn eenvoudig te maken door van een cirkel het onderste punt met een “Direct Selection Tool” omhoog te trekken tot voorbij het midden van de cirkel…. De druppels aan elkaar was echter een ander verhaal: hoe krijg je die druppels zo dat ze in elkaar overvloeien?

Uiteindelijk werd het een combinatie van het buitenste Path, aanvankelijk samengesteld uit drie cirkels, maar daarna omgebouwd tot een Path Shape. Het gewenste overvloei effect werd bereikt door een BlurBitmapEffect op de binnenste cirkels te zetten. (Ik snap dat dat niet werkt in Silverlight…)

Dit is de XAML code voor een enkele Droplet:


<Grid Width="100" Height="100">
 <Grid.ColumnDefinitions>
  <ColumnDefinition Width="*"/>
  <ColumnDefinition Width="10*"/>
  <ColumnDefinition Width="*"/>
 </Grid.ColumnDefinitions>
 <Grid.RowDefinitions>
  <RowDefinition Height="*"/>
  <RowDefinition Height="10*"/>
  <RowDefinition Height="*"/>
 </Grid.RowDefinitions>
 <Ellipse Stroke="#FF000000" Grid.ColumnSpan="3" Grid.RowSpan="3">
  <Ellipse.Fill>
   <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
     <GradientStop Color="#FF008000" Offset="0"/>
     <GradientStop Color="#FF64C800" Offset="0.5"/>
     <GradientStop Color="#FFC8FF00" Offset="1"/>
   </LinearGradientBrush>
  </Ellipse.Fill>
  <Ellipse.BitmapEffect>
   <DropShadowBitmapEffect ShadowDepth="15" Color="#FF64C800" Opacity="0.5" Softness=".5" Direction="315"/>
  </Ellipse.BitmapEffect>
 </Ellipse>
 <Ellipse Grid.ColumnSpan="3" Grid.RowSpan="3">
  <Ellipse.Fill>
   <RadialGradientBrush>
    <GradientStop Color="#00008000" Offset="0.697"/>
    <GradientStop Color="#FF008000" Offset="0.947"/>
    <GradientStop Color="#FF035303" Offset="1"/>
   </RadialGradientBrush>
  </Ellipse.Fill>
 </Ellipse>
 <Path Grid.Column="1" Grid.RowSpan="2" Width="80" Height="40" Stretch="Fill" VerticalAlignment="Top" Margin="0,5,0,0" Data="M146.95618,2.9995805E-06 C226.86218,0.013676752 273.86514,51.703491 289.14128,86.956135 297.95685,107.29974 276.17844,138.9885 252.71411,133.96005 236.26232,130.4344 223.33633,102.23228 145.78051,103.40737 68.224695,104.58246 52.948524,129.25931 31.324356,135.89577 10.824717,142.18711 -9.2624218,105.47439 4.5678474,81.502538 22.194617,50.950246 63.516652,-0.014275423 146.95618,2.9995805E-06 z" >
  <Path.Fill>
   <LinearGradientBrush EndPoint="0,1" StartPoint="0,0">
    <GradientStop Color="#00FFFFFF" Offset="1"/>
    <GradientStop Color="#FFFFFFFF" Offset="0"/>
    </LinearGradientBrush>
  </Path.Fill>
 </Path>
</Grid>