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!

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!

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!

Mix Essentials Europe is Serious: Serious Games in Silverlight

It took a while, but finally the session on Serious Games is added to the reserved slot at the end of the first day of Mix Essentials Europe on the 28th of May.

Together with TNO, André van der Plas and myself will present our experience and some cases, where we successfully used serious games to educate employees and citizens.

It is going to be very interesting! See you there!

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!

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!

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>

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>