October 2008 - Posts
I am proud to announce we have released the official version our Silverlight Tools for Silverlight 2. Prior to this release we had released an RC1 candidate alongside the RTW version of Silverlight.
If you have the RC1 or any previous version please upgrade today. The link to download the RTW version of Silverlight is: http://www.microsoft.com/downloads/details.aspx?FamilyId=c22d6a7b-546f-4407-8ef6-d60c8ee221ed&displaylang=en
The Silverlight Tools package includes:
- Silverlight 2 developer runtime
- Silverlight 2 software development kit
- KB956453 for Visual Studio 2008 SP1
and/or
KB956485 for Visual Web Developer 2008 Express with SP1 - Silverlight Tools for Visual Studio 2008 SP1
and/or
Silverlight Tools for Visual Web Developer 2008 Express with SP1
Features:
- Visual Basic and C# Project templates
- Intellisense and code generators for XAML
- XAML design preview
- Debugging of Silverlight applications
- Remote debugging of Silverlight applications for Mac
- Web reference support
- WCF Templates
- Team Build and command line build support
- Integration with Expression Blend
Before installing Silverlight Tools:
- Upgrade Microsoft Visual Studio 2008 to Service Pack 1 and make sure that the Visual Web Developer feature is installed.
or
Install Microsoft Visual Web Developer 2008 Express with SP1. - Uninstall any Beta or Preview versions of Expression Blend. You will need to have Blend 2 and install Microsoft Expression Blend™ 2 Service Pack 1.
Supported Operating Systems:
Windows Server 2008; Windows Vista; Windows XP
Thank you,
--Mike Snow
Subscribe in a reader
Microsoft Expression Design is a professional illustration and graphic design tool that lets you build compelling elements. This tool is especially great for creating vector based graphics for your elements.
If you do not have Expression Designer, check out: http://www.microsoft.com/expression/products/FAQ.aspx?key=design for more info.
Once you have created an element from this tool, you can copy the XAML of the objects you created directly into your Silverlight application through the Windows clipboard.
To do this, open your project and select the element you want to copy in Expression Designer. To select an element, mouse left click on the canvas and hold the mouse button down while moving the selection rectangle over your element. When it’s selected, it should be highlighted in red like this element:
Next, choose Edit->Options->Clipboard (XAML)…
This will bring up the Options dialog. From the “Clipboard format” option, drop down the combo box and choose “XAML Silverlight Canvas”. Click the OK button when done.
From the Edit menu choose Edit->Copy XAML.
Finally, open up your Silverlight Application project in Visual Studio. Open the XAML page you want to copy the element into. When ready, press Ctrl+v to paste your elements XAML into your XAML page.
Result:
Thank you,
--Mike Snow
Subscribe in a reader
In Tip of the Day #23 I showed you how to capture the mouse wheel event. In this tip we will take it one step further by implementing a IMouseWheelObserver interface that your Silverlight elements and controls can inherit from. This way, anytime the mouse wheel is used over your control, your control will be notified.
The following code is the interface declaration for IMouseWheelObserver:
public interface IMouseWheelObserver
{
void OnMouseWheel(MouseWheelArgs args);
event MouseEventHandler MouseEnter;
event MouseEventHandler MouseLeave;
}
The OnMouseWheel() event passes the following EventArgs when the event is fired for your control. These args:
- Track the Shift, Ctrl and Alt key combinations.
- Track the delta in change made by the mouse wheel scoll.
public class MouseWheelArgs : EventArgs
{
private readonly double
_Delta;
private readonly bool
_ShiftKey,
_CtrlKey,
_AltKey;
public double Delta
{
get { return this._Delta; }
}
public bool ShiftKey
{
get { return this._ShiftKey; }
}
public bool CtrlKey
{
get { return this._CtrlKey; }
}
public bool AltKey
{
get { return this._AltKey; }
}
public MouseWheelArgs(double delta, bool shiftKey, bool ctrlKey, bool altKey)
{
this._Delta = delta;
this._ShiftKey = shiftKey;
this._CtrlKey = ctrlKey;
this._AltKey = altKey;
}
}
Next, let’s take a look at the implementation of the WheelMouseListener class. In this class we:
- Call the HTMLPage methods to attach to the mouse scroll events on create.
- Call the HTMLPage methods to detach the mouse scroll events when the class is destroyed.
- Declare a element stack. We keep on the top of a stack the element that the mouse is currently over. This way we know which element to call when the mouse scroll event has occured.
public class WheelMouseListener
{
private Stack<IMouseWheelObserver> _ElementStack;
private WheelMouseListener()
{
this._ElementStack = new Stack<IMouseWheelObserver>();
HtmlPage.Window.AttachEvent("DOMMouseScroll", OnMouseWheel);
HtmlPage.Window.AttachEvent("onmousewheel", OnMouseWheel);
HtmlPage.Document.AttachEvent("onmousewheel", OnMouseWheel);
Application.Current.Exit += new EventHandler(OnApplicationExit);
}
/// <summary>
/// Detaches from the browser-generated scroll events.
/// </summary>
private void Dispose()
{
HtmlPage.Window.DetachEvent("DOMMouseScroll", OnMouseWheel);
HtmlPage.Window.DetachEvent("onmousewheel", OnMouseWheel);
HtmlPage.Document.DetachEvent("onmousewheel", OnMouseWheel);
}
public void AddObserver(IMouseWheelObserver element)
{
element.MouseEnter += new MouseEventHandler(OnElementMouseEnter);
element.MouseLeave += new MouseEventHandler(OnElementMouseLeave);
}
private void OnMouseWheel(object sender, HtmlEventArgs args)
{
double delta = 0;
ScriptObject e = args.EventObject;
if (e.GetProperty("detail") != null)
{
// Mozilla and Safari
delta = ((double)e.GetProperty("detail"));
}
else if (e.GetProperty("wheelDelta") != null)
{
// IE and Opera
delta = ((double)e.GetProperty("wheelDelta"));
}
delta = Math.Sign(delta);
if (this._ElementStack.Count > 0)
this._ElementStack.Peek().OnMouseWheel(new MouseWheelArgs(delta, args.ShiftKey, args.CtrlKey, args.AltKey));
}
private void OnElementMouseLeave(object sender, MouseEventArgs e)
{
this._ElementStack.Pop();
}
private void OnElementMouseEnter(object sender, MouseEventArgs e)
{
this._ElementStack.Push((IMouseWheelObserver)sender);
}
private void OnApplicationExit(object sender, EventArgs e)
{
this.Dispose();
}
private static WheelMouseListener _Instance = null;
public static WheelMouseListener Instance
{
get
{
if (_Instance == null)
{
_Instance = new WheelMouseListener();
}
return _Instance;
}
}
}
There are three modifications you need to make to your controls:
- Inherit from the IMouseWheelObserver interface
- Enlist in the event listener by calling WheelMouseListener.Instance.AddObserver(this); from your controls class constructor.
- Add the method OnMouseWheel() to your control which will be called when the event is fired.
Example:
public partial class Toolbar : UserControl, IMouseWheelObserver
{
public Toolbar()
{
InitializeComponent();
WheelMouseListener.Instance.AddObserver(this);
}
public void OnMouseWheel(MouseWheelArgs args)
{
// Process the event here...
}
}
Finally, I would like to thank Laith Alasad (Laith.Alasad@hyro.com) for this idea and the code contribution above to my original Mouse Wheel code!
Thank you,
--Mike Snow
Subscribe in a reader
In Tip of the Day #42 I discussed how to create Silverlight-enabled WCF web service. In this tip I will discuss the steps necessary to take in order to publish and deploy the web service with your Silverlight application on your server.
For security reasons, in order for Silverlight to talk with your web service on your server it will first request the file clientaccesspolicy.xml. This prevents attacks such as cross-site forgery from happening. If this file is not present it then checks for the Adobes default crossdomain.xml file. If at least one of these files are not found you will get an exception thrown by Silverlight. See Tip of the Day #63 for details on this error and how to see it happening. One of these files will need to be at the root directory of your web site (I.e. c:\inetpub\wwwroot).
This following configurations for these files allow access from any other domain to all resources on the current domain. You will want to configure these to meet your needs.
ClientAccessPolicy.xml –
<?xml version="1.0" encoding="utf-8"?>
<access-policy>
<cross-domain-access>
<policy>
<allow-from http-request-headers="*">
<domain uri="*"/>
</allow-from>
<grant-to>
<resource path="/" include-subpaths="true"/>
</grant-to>
</policy>
</cross-domain-access>
</access-policy>
CrossDomain.xml:
<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
<allow-http-request-headers-from domain="*" headers="*"/>
</cross-domain-policy>
For more on making your service available across domain boundaries see: http://msdn.microsoft.com/en-us/library/cc197955(VS.95).aspx
Thank you,
--Mike Snow
Subscribe in a reader
Recently when deploying a Silverlight application with a web service I forgot to include a client access policy and cross domain file. As a result I got the following exception when attempting to browse to my application:
The exception did not make the error very obvious and I spent more time then I should have debugging it. Fortunately I discovered a rather awesome, freeware tool that quickly identified the problem. The tool, called Fiddler, is available at http://www.fiddlertool.com/fiddler. In a nutshell, Fiddler is a HTTP debugging proxy which logs all HTTP traffic between your computer and the Internet. You can:
- Inspect all HTTP traffic.
- Set breakpoints.
- Modify incoming and outgoing data.
- Extend it with any .NET language.
When running Fiddler then browsing to to my web site I was able to see right away that Silverlight was looking for the files clientaccesspolicy.xml and crossdomain.xml:

Thank you,
--Mike Snow
Subscribe in a reader
Hyperlinks are a graphic or string that connects readers to another web site when clicked. Generally these are a few words that are identified by a blue color and a underline. Here is an example of a hyperlink:
Click Me
In Silverlight Hyperlinks can be created through the HyperlinkButton control.
Here is an example of a how to declare a HyperlinkButton control in XAML:
<HyperlinkButton Content="Click Me" NavigateUri="http://www.silverlight.net">
</HyperlinkButton>
Couple notes:
- Content is what is displayed to the user.
- NavigateUri is the destination the user is taken too when the link is clicked.
When run you will see this:
You can target the link to open the link in a new page or the same page by setting the TargetName property.
- TargetName = _blank, _media, _search = Open the link in a new window
- TargetName = _parent, _self, _top, “” = Open the link in the window the link was clicked.
Example opening a new page:
<HyperlinkButton Content="Click Me" TargetName="_blank" NavigateUri="http://www.silverlight.net">
</HyperlinkButton>
Opening the same page:
<HyperlinkButton Content="Click Me" TargetName="_self" NavigateUri="http://www.silverlight.net">
</HyperlinkButton> Additionally, the Hyperlink does not have to be represented by text. You can use any control such as a Image, etc. by setting the HyperlinkButton.Content. For example:
<HyperlinkButton NavigateUri="http://www.silverlight.net">
<HyperlinkButton.Content>
<Canvas>
<Rectangle Width="100" Height="100" Fill="Black" Stroke="Blue" StrokeThickness="2" ></Rectangle>
<TextBlock Canvas.Top="40" Canvas.Left="25">Click Me</TextBlock>
</Canvas>
</HyperlinkButton.Content>
</HyperlinkButton>
As shown when run:
Thank you,
--Mike Snow
Subscribe in a reader
If you have a FrameworkElement such as an Image, Button, TextBlock, etc. you can add a tooltip to the element. Tooltips are usually small, boxed text that popup when a user hovers over the control. The purpose of the tooltip is to tell the user what the control does.
For example, let’s say we have a toolbar of flags that represent the language a user can select:
If a user did not recognize a flag they could hover over it and the tooltip would say what language the flag represents. For example:
To add a Tooltip to a FrameworkElement all you have to do is declare the property TooltipService.Tooltip. For Example:
<Image Source="images/france.png" ToolTipService.ToolTip="French">
A tooltip does not have to only be text, rather a tooltip can be any control you declare. For example, to make a tooltip an image you would declare it as:
<Image Source="images/france.png" Width="16" Height="16">
<ToolTipService.ToolTip>
<Image Source="images/france.png"></Image>
</ToolTipService.ToolTip>
</Image>
The result when hovering over the French flag would be the French flag at its original size:
Thank you,
--Mike Snow
Subscribe in a reader
Today I am very proud to announce that Silverlight 2 has been officially released! Grab it today at http://silverlight.net/GetStarted. This is a phenomenal release that provides a powerful solution to creating rich web application. At the link above you can install:
- The official release version of Microsoft Silverlight 2 (Mac or Windows version).
- The RC1 of the Visual Studio add-on for Visual Studio 2008 with SP1 or Visual Web Developer Express with SP1. Although this is an RC1 for tools, it does come with the official release version of Silverlight 2. You can expect the RTW version of tools very soon!
- Microsoft Expression Blend 2 Service Pack 1.
- Deep Zoom Composer.
Breaking Changes
Make certain to upgrade your beta 1 and beta 2 applications as they will not run under the release version of Silverlight 2. For a complete list of breaking changes see the Breaking Changes document. I also call out these breaking changes in my blog here for RC0. The #1 on my list is to update your MIME types and MinimumVersion:
#1 - Your Web Page.
If you have a project already developed for beta-1 or beta-2 you will need to make an adjustment to your web page that hosts the Silverlight control. For an HTML page change you will need to change the MIME type. To do this, open your HTML Page, change “x-silverlight-2-b1” or “application/x-silverlight-2-b2” to “application/x-silverlight-2”.
<object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">
If you use an ASPX based Page, open your ASPX page and change the Minimum Version to “2.0.30923.0”:
<asp:Silverlight ID="Xaml1" runat="server" Source="~/ClientBin/TextBlockTest.xap" MinimumVersion="2.0.31005.0" Width="100%" Height="100%" />
Highlights
Highlights of the new Silverlight 2 features from the Press Release:
- NET Framework support with a rich base class library. This is a compatible subset of the full .NET Framework.
- Powerful built-in controls. These include DataGrid, ListBox, Slider, ScrollViewer, Calendar controls and more.
- Advanced skinning and templating support. This makes it easy to customize the look and feel of an application.
- Deep zoom. This enables unparalleled interactivity and navigation of ultrahigh resolution imagery.
- Comprehensive networking support. Out-of-the-box support allows calling REST, WS*/SOAP, POX, RSS and standard
HTTP services, enabling users to create applications that easily integrate with existing back-end systems.
- Expanded .NET Framework language support. Unlike other runtimes, Silverlight 2 supports a variety of programming languages, including Visual Basic, C#, JavaScript, IronPython and IronRuby, making it easier for developers already familiar with one of these languages to repurpose their existing skill sets.
- Advanced content protection. This now includes Silverlight DRM, powered by PlayReady, offering robust content protection for connected Silverlight experiences.
- Improved server scalability and expanded advertiser support. This includes new streaming and progressive download capabilities, superior search engine optimization techniques, and next-generation in-stream advertising support.
- Vibrant partner ecosystem. Visual Studio Industry Partners such as ComponentOne LLC, Infragistics Inc. and Telerik Inc. are providing products that further enhance developer capabilities when creating Silverlight applications using Visual Studio.
- Cross-platform and cross-browser support. This includes support for Mac, Windows and Linux in Firefox, Safari and Windows Internet Explorer.
For More Details
Known issues and workarounds. (I will keep this section up-to-date if any other issues are encountered):
- MediaElement – If you just store your media files (MP3’s, etc) in your web sites ClientBin folder you should now include them in your Silverlight application project as well. This is necessary to avoid a crash that could occur in Visual Studio.
Thank you,
--Mike Snow
Subscribe in a reader
If you have a control written in XAML that is included in your project you can load and create it directly from file by using the method: System.Windows.Markup.XamlReader.Load().This method can also be used to directly create a Silverlight control from a string.
To demonstrate this I have created two functions called LoadFromXAML(). The first function takes takes as a parameter a URI that points to the XAML file in your project you want to load. The second takes as a parameter a string representation of the control.
public static object LoadFromXaml(Uri uri)
{
System.Windows.Resources.StreamResourceInfo streamInfo = System.Windows.Application.GetResourceStream(uri);
if ((streamInfo != null) && (streamInfo.Stream != null))
{
using (System.IO.StreamReader reader = new System.IO.StreamReader(streamInfo.Stream))
{
return System.Windows.Markup.XamlReader.Load(reader.ReadToEnd());
}
}
return null;
}
public static object LoadFromXamlString(string xamlControl)
{
return System.Windows.Markup.XamlReader.Load(xamlControl);
}
The above methods return a generic object that can be typecast to the object you are loading. For example:
Button myButton = (Button)LoadFromXaml(new Uri("/LoadXaml;component/MyButton.xaml", UriKind.Relative));
or
string buttonXAML = "<Button xmlns='http://schemas.microsoft.com/client/2007' Width=\"100\" Height=\"100\" Content=\"Click Me\"></Button>";
Button myButton = (Button) LoadFromXaml(buttonXAML);
Note that in the XAML you must declare a default XML namespace as highlighted below:
<Button xmlns='http://schemas.microsoft.com/client/2007' Width="100" Height="100" Content="Click Me"></Button>
If you do not declare this namespace, you will see the following error:
AG_E_PARSER_MISSING_DEFAULT_NAMESPACE [Line: 0 Position: 0]
Thank you,
--Mike Snow
Subscribe in a reader
If you try to use the following characters in a string in XAML you will get a slew of errors in your Error List:
- <
- >
- &
- “
For example, if you tried to do this:
<Button Width="100" Height="100" Content="Click &Me"></Button>
You would get these errors:
Error 1 '"' is an unexpected token. The expected token is ';'. Line 32, position 60.
Error 3 Entity references or sequences beginning with an ampersand '&' must be terminated with a semicolon ';'.
You can encode invalid characters for use in XAML by using the following syntax:
| Character | Encoding |
| < | < |
| > | > |
| & | & |
| “ | " |
In addition, the following character encoding is also useful:
| Character | Encoding |
| Space |   |
So to fix the Button above you would insert “&” wherever you want to use an “&”
<Button Width="100" Height="100" Content="Click &Me"></Button>
Thank you,
--Mike Snow
Subscribe in a reader
TextBlocks are a great control to use in Silverlight to display read only text. In Tip of the Day #45 I covered the basic usage of TextBlocks including formatting and text runs.
For this tip I would like to show you how to make a TextBlock with wrapping text and line breaks.
To make a TextBlock wrap its text you will need to set TextWrapping ="Wrap" on the TextBlock. The following example below shows a TextBlock in a ContentControl that is only 100 pixels wide. With TextWrapping set to “Wrap”, the TextBlock will wrap to a new line each time its contents reach 100 pixels in width.
XAML:
<Canvas Margin="10">
<ContentControl Width="100">
<TextBlock TextWrapping="Wrap">
A lie can travel half way around the world while the truth is putting on its shoes.
--Mark Twain
</TextBlock>
</ContentControl>
</Canvas>
Result with TextWrapping = “Wrap”:
Without TextWrapping:
As you may notice the text above does not include any of the line breaks seen in the XAML. To insert a line break all you need to do is insert a <LineBreak> tag within the text.
Example:
<Canvas Margin="10">
<ContentControl Width="100">
<TextBlock TextWrapping="Wrap">
A lie can travel half way around the world while the truth is putting on its shoes.
<LineBreak></LineBreak>
<LineBreak></LineBreak>
--Mark Twain
</TextBlock>
</ContentControl>
</Canvas>
Result:
Thank you,
--Mike Snow
Subscribe in a reader
Let’s say your site is entirely written in Silverlight but you want to be able to load and run a different Silverlight application within your main Silverlight application/site. Currently this scenario is not directly supported in Silverlight. However, I have a work around that will more or less accomplish this scenario.
The way I do this is to add a second, hidden Silverlight control to your web page. I set the Source for this second Silverlight control to be empty (“”) until I want the Silverlight control to load and display. I also put the control in a DIV that is hidden. You can load and unload this control as well and you can dynamically set it to point to different XAP’s to load different applications in your site.
Step 1.
In my web site (I.e. default.aspx file):
Main Silverlight Control that represents my web site:
<div style="height: 100%; z-index: 1; position: absolute;">
<asp:Silverlight ID="Xaml1" runat="server" Source="~/ClientBin/SLDev.xap" MinimumVersion="2.0.30523" Width="100%" Height="100%" />
</div>
Second Silverlight control that we will load and display within the main site:
<div id="myDIV" style="z-index: 2; display: none; position: absolute; padding-left: 0px; padding-top: 200px;">
<asp:Silverlight ID="Silverlight1" runat="server" Source="" MinimumVersion="2.0.30523" Width="800px" Height="600px" />
</div>
Things to notice:
- I set the style z-index order to be higher for the second Silverlight control than the first so that it appears on top.
- I set style display = none for the DIV of the second Silverlight control so that it is not displayed and does not interfere with mouse/keyboard input for the first Silverlight control.
- I set style position = absolute so that the controls can float on top of each other. You will want to adjust the padding-left and padding-right to properly position the control where you want it on your site.
- I set Source =”” for the second Silverlight control to keep it from loading an application until I am ready.
Step 2.
In my web site (I.e default.aspx) I add two Javascript functions that my Silverlight application can call to load and hide the second Silverlight control. Few notes:
- LoadSilverlightControl() – This function takes a parameter that contains the full path to the XAP we want to load. Example: “ClientBin\TankWar.xap”
- For the Silverlight Control, I call setAttribute() to change the source of the Silverlight control.
- For the DIV I modify style.display setting it to “block” so that it will display or “none” to hide it.
<script type="text/javascript">
function LoadSilverlightControl(ctrl) {
var control = document.getElementById("Silverlight1");
var div = document.getElementById("myDIV");
div.style.display = "block";
control.setAttribute("Source", ctrl);
}
function HideSilverlightControl() {
var control = document.getElementById("Silverlight1");
var div = document.getElementById("myDIV");
div.style.display = "none";
control.setAttribute("Source", "");
}
</script>
Step 3.
The call from Silverlight->Javascript to make the control load and run:
HtmlPage.Window.Invoke("LoadSilverlightControl", "ClientBin/TankWar.xap");
To hide it:
HtmlPage.Window.Invoke("HideSilverlightControl");
Result.
The following screen shots show this in action. Click on the “Games” button….
And my Tank War application is loaded and displayed.
Thank you,
--Mike Snow
Subscribe in a reader
In Silverlight you can interact directly with the HTML DOM (Document Object Model). This can be done through the HtmlPage.Document object:
HtmlDocument doc = HtmlPage.Document;
Make certain to first add a reference to the following namespace:
using System.Windows.Browser;
To illustrate this point I will walk you through a demo that will change the background color of your HTML Page when you click a button. To create this demo, follow these steps:
Step 1. Create a new Silverlight Application using Visual Studio 2008.
Step 2. Open up the your Test page (such as SilverlightApplication1TestPage.aspx) and modify the DIV tag surrounding your Silverlight object to have an ID and background color. In addition, set the width and height to be 20% and your Silverlight control to be 50% wide so that the Silverlight control does not overlap the entire background of the HTML page:
<div id="myDIV" style="background:blue;width:20%;height:20%">
<asp:Silverlight ID="Xaml1" runat="server"
Source="~/ClientBin/SilverlightApplication27.xap" MinimumVersion="2.0.30930.0"
Width="50%" Height="100%" />
</div>
Step 3. In Page.xaml add a button with a click event:
<UserControl x:Class="SilverlightApplication1.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300">
<Canvas>
<Button Click="Button_Click" Content="Change Colors"></Button>
</Canvas>
</UserControl>
Step 4. In Page.xaml.cs and the following code which will change the background color of your HTML Page. You will notice we are:
- Getting the HTML Document for the page.
- Getting the DIV by it’s ID.
- Setting the style attribute of the DIV changing its background color from its original blue color to green.
private void Button_Click(object sender, RoutedEventArgs e)
{
HtmlDocument doc = HtmlPage.Document;
HtmlElement div = doc.GetElementById("myDIV");
div.SetStyleAttribute("background", "green");
}
Step 5. Run the application. The background of the Silverlight control is white where as the background of the HTML page is blue.
Screen shot before click:
Screen shot after click:
Thank you,
--Mike Snow
Subscribe in a reader
Styles are extremely important because they allow developers to control the look and layout of controls across their application. By using styles you can simply change the style declaration and all controls in the application are updated automatically. This is a much faster alternative to updating each and every control in your application individually.
For this tip we will be exploring the basic fundamental use of styles in Silverlight. I will follow up with more complex scenarios in the next Tip of the Day.
In Silverlight, styles are declared within the controls <UserControl.Resources> tags. If you want to make them global to all controls you can put them in your App.XAML file within the <Application.Resources> tags.
To illustrate this point let’s create a global style on how we will display TextBlocks throughout our sample application:
<Application xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
x:Class="MyApp.App">
<Application.Resources>
<Style x:Name="TextBoxStyle" TargetType="TextBlock">
<Setter Property="FontFamily" Value="Calibri.ttf#Calibri"></Setter>
<Setter Property="FontSize" Value="16"></Setter>
</Style>
</Application.Resources>
</Application>
For the XAML above:
- Style - Declare each style within <Style></Style>tags in the <Application.Resources> or <UserControl.Resources> section.
- Name – Set the name of the style (via x:Name=””) so we can reference it from our controls.
- TargetType -The name of the FrameworkElement you are targeting. In our case above we are targeting a “TextBlock”.
- Setter - Each property we want to set for this style is declared as a Setter. You can set multiple setters per style. For example, FontSize, FontFamily, etc.
Next, the following XAML below shows how to create multiple TextBlocks with the same style applied to it.
<TextBlock x:Name="myTextBlock" Text="Hello There." Style="{StaticResource TextBoxStyle}"></TextBlock>
<TextBlock x:Name="myTextBlock2" Text="How are you?" Style="{StaticResource TextBoxStyle}"></TextBlock>
<TextBlock x:Name="myTextBlock2" Text="Good thanks!" Style="{StaticResource TextBoxStyle}"></TextBlock>
Finally, if we want to change the font size for these TextBlocks all we have to do is change it in the style setter rather than in each individual TextBlock.
Before: <Setter Property="FontSize" Value="16"></Setter>
After: <Setter Property="FontSize" Value="25"></Setter>
Thank you,
--Mike Snow
Subscribe in a reader
The recent RC0 release of Silverlight Tools for Visual Studio is now compatible with Visual Web Developer Express with SP1 installed! Express is FREE and can be downloaded here: http://www.microsoft.com/express/download/.
This version only supports the English version of Visual Studio. Non-English users will have to use this version until the language specific releases are completed.
Thank you,
--Mike Snow
Subscribe in a reader