Tag Archives: XAML

Windows Phone 7/8

Using Viewbox for automatic control scaling

Presenting content of varied size can often be tricky. For example, displaying names of metro stations with fixed font size, and it always is a fixed font size, can result in a part of the text being clipped off. Or if you use text wrapping, a large block of text can extend way beyond your intended design. Trimming might help, but you cannot always do that.

Consider the following page:

Simple page without using Viewbox

Simple page using a bunch of controls with default styles

It uses a very simple layout – two equally wide columns. Notice how the default font might be too small for the text on the left and how variation in button captions create problems for buttons on the right. We would like to increase font size for the text on the right, but it is hard to anticipate how large the text would be. Or if there are large words in the text, they might “bleed” onto the right side. As for the buttons, you would want the entire text to be seen.

So how do we do that? Luckily, there is a control that will auto scale any content we give it – Viewbox. Whatever content you give it, Viewbox will auto scale it, either up or down, to fill the space the Viewbox control would normally take. The XAML for the above page looked like this:

<Border BorderBrush="Red" BorderThickness="1"
        HorizontalAlignment="Center"
        VerticalAlignment="Center">
    <TextBlock Text="{Binding FullName}"
                TextAlignment="Right"/>
</Border>

<StackPanel Grid.Column="1">
    <StackPanel.Resources>
        <Style TargetType="Button">
            <Setter Property="Width" Value="200" />
            <Setter Property="Height" Value="80" />
            <Setter Property="Margin" Value="10"/>
        </Style>
    </StackPanel.Resources>

    <Button Content="Pick 1" />
    <Button Content="or 2" />
    <Button Content="or any large number" />
    <Button Content="first line&#13;second line" />
</StackPanel>

We wrap the problematic control inside the Viewbox control. The final XAML should look like this:

<Viewbox>
	<Border BorderBrush="Red" BorderThickness="1">
		<TextBlock Text="{Binding FullName}"
			   TextAlignment="Right"/>
	</Border>
</Viewbox>

<StackPanel Grid.Column="1">
	<StackPanel.Resources>
		<Style TargetType="Button">
			<Setter Property="Width" Value="200" />
			<Setter Property="Height" Value="80" />
			<Setter Property="Margin" Value="10"/>
			<Setter Property="Template">
				<Setter.Value>
					<ControlTemplate TargetType="Button">
						<Grid>
							<Border BorderBrush="{TemplateBinding BorderBrush}"
	BorderThickness="{TemplateBinding BorderThickness}"
	Background="{TemplateBinding Background}"
									Margin="{TemplateBinding Margin}">
								<Viewbox>
									<ContentPresenter
		Content="{TemplateBinding Content}"
		ContentTemplate="{TemplateBinding ContentTemplate}"
		Margin="{TemplateBinding Padding}"
		HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
		VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
								</Viewbox>
							</Border>
						</Grid>
					</ControlTemplate>
				</Setter.Value>
			</Setter>
		</Style>
	</StackPanel.Resources>

	<Button Content="Pick 1" />
	<Button Content="or 2" />
	<Button Content="or any large number" />
	<Button Content="first line&#13;second line" />
</StackPanel>

The TextBlock on the left was wrapped in the Viewbox control while the control template for the buttons was modified to put the content inside another Viewbox. The final result can be seen on the image below.

Simple page using Viewbox control

Text scales correctly when using Viewbox control

As you can see from the image, text is now fully visible in the buttons while the text on the left is now scaled up to fill the allocated space. This isn’t full-proof solution because you still need to account for differences between the smallest and the largest text. You could pad the text on both size with spaces, just to ensure that short text doesn’t become really large.

Windows 8

Create app bar button icons using Segue UI Symbols font

Creating app bar buttons for WinRT applications is easier than creating them for Windows Phone applications. While Windows Phone uses transparent images for app bar buttons, WinRT applications use built-in Segoue UI Symbol font for that purpose. This simplifies things quite a bit since we don’t have to trouble ourselves with scaling, picking correct size for the app bar images and theming (in case we need black and white versions). If you took a look at the default styles that come for WinRT applications, you could notice that they don’t use any images, they are simply referencing a particular symbol in the font. read more »

Windows Phone 7/8

WP8 XAML and DirectX app crashes when adding navigation

Windows phone topic Creating applications from default templates without understanding them might introduce serious bugs in your application. Consider the simple Windows Phone XAML and Direc3D App project template. Let’s create basic app and pretend we are building a new game. We probably want to add some other XAML pages e.g. for settings, high scores, about dialog, etc.

I will first add simple button with caption “High scores” to the bottom of MainPage using the following XAML:

<Button Content="High scores"
        HorizontalAlignment="Center"
        VerticalAlignment="Bottom"
        Click="_btnHighScores_Click" />

The application looks simple enough so far. read more »

Windows 8

DirectX and XAML in Windows (Phone) 8 – part 2 of N – WinRT component and C# integration

This entry is part of a series, DirectX and XAML»

In the previous post I have created a basic Windows 8 application featuring both DirectX and XAML. However, the sample was written in C++/CX and there aren’t any project templates for writing applications with both XAML and DirectX since the latter one is exposed only in C++. Luckily, there is a way for you to write C++ code that deals with DirectX which you could then reference in C#/VB – by creating WinRT component.

Creating an WinRT component

You can create Windows Runtime components in either C++ or your favorite managed language. Start Visual Studio and create new project with Visual C++/Windows Store/Windows Runtime Component. Delete the sample class created by the template (seen on the image below).
read more »

Windows 8

DirectX and XAML in Windows (Phone) 8 – part 1 of N – Simple 2D surface

This entry is part of a series, DirectX and XAML»

If you want to add a simple DirectX drawn surface to your existing XAML application, use SurfaceImageSource. This is a XAML type which allows you to continue using XAML composition and it also gives you the full control to the DirectX surface for rendering.

Once instantiated, use SurfaceImageSource as a source for ImageBrush. Since brushes are reusable, you can use the same DirectX surface for multiple XAML elements. This sample code creates new SurfaceImageSource and assigns it as the source for ImageBrush:

SurfaceImageSource^ surfaceImageSource =  
    ref new SurfaceImageSource(width, height, true);    
ImageBrush^ brush = ref new ImageBrush(); 
brush->ImageSource = surfaceImageSource; 

// if you have a rectangle or a ellipse
element->Fill = brush;

However, you can notice that SurfaceImageSource doesn’t expose any methods for drawing, for that you need to use the backing native interface. The above code can be easily written in C#, but you cannot access the underlying native interface necessary for rendering to the DirectX surface. That interface and also entire DirectX is currently available only in C++ template projects that ship with Visual Studio 2012. read more »

Windows 8 Windows Phone 7/8

DirectX and XAML in Windows (Phone) 8 – part 0 of N – Overview

This entry is part of a series, DirectX and XAML»

DirectX is a powerful beast that enables creation of stunning graphics oriented applications (not just games :) ). On the other hand, XAML is used to quickly create basic application UI. Having both in a single application seems like an obvious choice. For example: when building a game, you can use XAML to create level selection screens, mode selection screen, options page, etc while leaving DirectX to power the game itself. It is only natural to combine the best of the two in a single application.

Since we now have both Windows 8 and Windows Phone 8 out in the wild, I will dedicate some time on this blog to describing how to combine XAML and DirectX on both platforms. This is the first blog post in the series and will provide some basic overview of future posts.

Since DirectX is exposed only in C++ project templates, first couple of posts will feature C++/CX only. Later on, I will describe how to bridge the gap to the managed world using SharpDX for Windows 8. All examples will be rather simplistic, but you can use your imaginations to build wonderful new things.

During the series, I will be using Microsoft Visual Studio 2012 Express for Windows 8 and Microsoft Visual Studio 2012 Express for Windows Phone, which you can download from the following links: Express for Windows 8 and Express for Windows Phone. All samples for Windows 8 can can also run on Windows RT since we are building a Windows Store app. read more »

Windows Phone 7/8

ListBox empty template – using control templates and behaviors (part 2)

This article requires update, please wait for it. For those who can’t wait, the problem is that you need to define an additional dependency property for empty template. You cannot simply set control template to null. I apologize for the inconvenience.

Windows phone topic In the previous post I have shown how to fake “empty ListBox template” using visual states. The proposed solution is very intrusive since it requires editing the built-in (or customized) control template. You have to design the template carefully to avoid any visual state corruption.

And if we want to introduce the third template, let’s say we want to have also “download in progress” template (similarly to the way Marketplace search works), the control template would become unmanageable. It would be best to completely separate each template from normal template, and this is exactly what we are going to do today.

The final result will give us something like this:
All states for list box; from left to right: progress, default, empty
read more »

Windows Phone 7/8

Using ImageTile control from Coding4Fun v1.6

New version of Coding4Fun Toolkit was released three days ago, you can grab it at Codeplex. One control immediately grabbed my interest – ImageTile. It offers a variation of standard hub tile and looks similar to the people hub tile, although you can easily customize it. The following screenshot shows the ImageTile control in action.
read more »

Tips Windows Phone 7/8

Text button that tilts when you tap it

While designing a Windows Phone app, I came a across a simple design problem: how to display text control which will serve as a button. You can tap it, it will display visual cue i.e. it will tilt when tapped and the application will then perform some action.

If you want to catch the tap event on the text control, you must first set the IsHitTestVisible property to true. If you forget to set it, you will not receive anything in your event handler.

However, the text won’t display any visual cue that you have tapped it, it remains static. You can add the Silverlight Toolkit for WP7 package which contains the TiltEffect class. But it still won’t work. The text simply will not tilt.

Luckily for us, we can use the control that is usually used for such purpose – button. However, we must style it to hide the border. We will simply change the default template and set the desired text as its content. The XAML code looks like this:

<Button>
    <Button.Template>
        <ControlTemplate>
            <Grid>
                <ContentPresenter />
            </Grid>
        </ControlTemplate>
    </Button.Template>
    <Button.Content>
        <StackPanel>
            <TextBlock Style="{StaticResource PhoneTextLargeStyle}"
                        Text="Call number"
                        toolkit:TiltEffect.IsTiltEnabled="True" />
            <TextBlock Style="{StaticResource PhoneTextNormalStyle}"
                        Foreground="{StaticResource PhoneAccentBrush}"
                        Text="555-505234"
                        toolkit:TiltEffect.IsTiltEnabled="True" />
        </StackPanel>
    </Button.Content>
</Button>

The final result is visible on the following image:

Windows Phone 7/8

ListBox empty template – using visual states (part 1)

ListBox can be customized in a lot of different ways: you can change the item template, the container or the control template. However, there are some common states which cannot be easily set. For example, if you want to display “No items match your query” as a property of the ListBox itself, there is no such template. Similarly, the template for “data is loading” does not exist. These are all common requirements for building a pleasant UX.

When you are searching the WP7 marketplace from your phone you will get a message when no applications can be found with the specified criteria. Also, before the search is complete, the progress indicator is displayed in the middle of the ListBox indicating that it is currently being filled. This is somewhat better UX than using the progress indicator in the system tray since the user knows that the list box is not ready rather than the generic “application is doing something so please wait.” We want to replicate such design easily. Luckily, you can achieve this functionality in several different ways:

  1. Place an invisible TextBlock element which will be visible when there are no elements found. Toggle the visibility in your OnCompleted handler.
  2. Create a user control which contains the logic and a dependency property for the “empty message”
  3. Inherit custom control from ListBox and create custom control template.

In the first solution you have to add elements to the page which should not belong there, maintenance is reduced and you have to c/p the same snippet all over the place. In the second solution you lose the ability to simply style the ListBox control inside the UserControl. There should be a simple, portable (in a sense that we can apply it to other ListBox-like control like controls), maintainable and customizable solution. The third solution prevents you from enhancing other inherited ListBox controls which might be detrimental.

In this post I will present one method for adding such “empty template” and “progress template” using visual states. read more »