Controls (XAML with C#/C++/VB)

Add new features to your Windows Store app, including date and time pickers and enhanced navigation support, with the new XAML controls in Windows 8.1. Updates to existing controls make them easier to use and more versatile. These new controls and control updates make it easier than ever to create a full-featured app.

New controls and control updates

Windows 8.1 introduces these new controls and features:

Windows 8.1 includes updates for these existing controls:

AppBar controls

[Get the XAML AppBar control sample now.]

Windows 8.1 introduces new controls for XAML that let you more easily create app bar command buttons that reflect the proper design guidelines and behaviors: the AppBarButton, AppBarToggleButton, and AppBarSeparator controls.

App bar buttons for XAML

 

App bar buttons differ from standard buttons in several ways:

  • Their default appearance is a circle instead of a rectangle.

  • You use the Label and Icon properties to set the content instead of the Content property. The Content property is ignored.

  • The button's IsCompact property controls its size.

The app bar button controls come in two sizes; normal and compact. By default, they have a text label and full padding. When the IsCompact property is set to true, the text label is hidden and the padding around the buttons is reduced. The AppBarSeparator also has a compact state in which the padding is reduced.

Here are the same commands shown before, but in their compact state.

Compact app bar buttons

 

When you use the app bar controls in the new CommandBar control, the CommandBar sets their IsCompact property automatically. If you use an app bar button outside of a CommandBar, like in an AppBar or on the app canvas, you need to set the IsCompact property appropriately in your code.

You can use app bar buttons outside of an app bar. A common example is to use an app bar button as a back button in a page header. When a button is used outside of an app bar, Windows guidelines indicate that it should always be in its compact state.

You use the Label and Icon properties to define the content of the app bar buttons. Set the Label property to a string to specify the text label. The label is shown by default but is hidden when the button is in its compact state, so you also need to specify a meaningful icon. To do that, set the button's Icon property to an element derived from the new IconElement class. Four kinds of icon elements are provided:

  • FontIcon—The icon is based on a glyph from the specified font family.

  • BitmapIcon—The icon is based on a bitmap image file with the specified Uri.

  • PathIcon—The icon is based on Path data.

  • SymbolIcon—The icon is based on a predefined list of glyphs from the Segoe UI Symbol font.

Creating an app bar button

This example shows how to create AppBarButton, AppBarSeparator, and AppBarToggleButton controls with each type of icon.


<!-- App bar button with symbol icon. -->
<AppBarButton Icon="Like" Label="SymbolIcon" Click="AppBarButton_Click"/>         

<!-- App bar button with bitmap icon. -->
<AppBarButton Label="BitmapIcon" Click="AppBarButton_Click">
    <AppBarButton.Icon>
        <BitmapIcon UriSource="ms-appx:///Assets/globe.png"/>
    </AppBarButton.Icon>
</AppBarButton>

<AppBarSeparator />

<!-- App bar toggle button with font icon. -->
<AppBarToggleButton Label="FontIcon" Click="AppBarButton_Click">
    <AppBarToggleButton.Icon>
        <FontIcon FontFamily="Candara" Glyph="&#x03A3;"/>
    </AppBarToggleButton.Icon>
</AppBarToggleButton>

<!-- App bar toggle button with path icon. -->
<AppBarToggleButton Label="PathIcon" Click="AppBarButton_Click">
    <AppBarToggleButton.Icon>
        <PathIcon Data="F1 M 20,20L 24,10L 24,24L 5,24"/>
    </AppBarToggleButton.Icon>
</AppBarToggleButton>

That example code creates these controls.

App bar button icon examples.

 

CommandBar

[Get the XAML AppBar control sample now.]

Windows 8.1 introduces a new control for XAML that lets you easily create properly designed app bars: the CommandBar control.

The command bar

 

The CommandBar simplifies the creation of basic app bars by providing:

  • Automatic layout of commands, with primary commands on the right and secondary commands on the left.

  • Automatic resizing of app bar commands when the app size changes.

When you need an app bar that contains only AppBarButton,AppBarToggleButton , and AppBarSeparator controls, use this new CommandBar. If you need more complex content, such as images, progress bars, or text blocks, use an AppBar control.

By default, items you add to the CommandBar are added to the PrimaryCommands collection. These commands are shown on the right side of the CommandBar. You can also add commands to the SecondaryCommands collection, and these items are shown on the left side.

The app bar button controls come in two sizes: normal and compact. By default, they have a text label and full padding. When the IsCompact property is set to true, the text label is hidden and the padding around the buttons is reduced. The AppBarSeparator also has a compact state in which the padding is reduced. When you use these controls in the new CommandBar control, it sets their IsCompact property automatically when there's not enough space to show them at full size.

Here are the same primary commands shown before, but in their compact state.

The command bar with compact buttons

 

Creating a CommandBar

This example creates the command bar shown earlier.


<Page.BottomAppBar>
    <CommandBar>
        <AppBarToggleButton Icon="Shuffle" Label="Shuffle" Click="AppBarButton_Click"/>
        <AppBarToggleButton Icon="RepeatAll" Label="Repeat" Click="AppBarButton_Click"/>
        <AppBarSeparator/>
        <AppBarButton Icon="Back" Label="Back" Click="AppBarButton_Click"/>
        <AppBarButton Icon="Stop" Label="Stop" Click="AppBarButton_Click"/>
        <AppBarButton Icon="Play" Label="Play" Click="AppBarButton_Click"/>
        <AppBarButton Icon="Forward" Label="Forward" Click="AppBarButton_Click"/>

        <CommandBar.SecondaryCommands>
            <AppBarButton Icon="Like" Label="Like" Click="AppBarButton_Click"/>
            <AppBarButton Icon="Dislike" Label="Dislike" Click="AppBarButton_Click"/>
        </CommandBar.SecondaryCommands>
    </CommandBar>
</Page.BottomAppBar>

DatePicker

[Get the XAML DatePicker and TimePicker controls sample now.]

Windows 8.1 introduces a new control for XAML that lets a user set a localized date in your app: the DatePicker control.

The date picker

 

The date picker gives you a standardized way to let users to pick a localized date using touch, mouse, or keyboard input methods. You can use the DatePicker control in its default form with a minimal amount of XAML or other code, or you can customize it in a variety of ways.

The DatePicker supports each of the calendar systems supported by Windows. These nine calendars are specified in the Windows.Globalization.CalendarIdentifiers class. The DatePicker uses the correct calendar for your app's default language, or you can set the CalendarIdentifier property to use a specific calendar system.

Creating a DatePicker

This example shows how to create a simple DatePicker with a header.


<DatePicker x:Name=arrivalDatePicker Header="Arrival Date"/>

This DatePicker looks like this when the day selector is opened.

A date picker with day selector open

 

You can set the date in code, or bind the control to an instance of DateTimeOffset. Here, the DatePicker is set in code to default to 2 months from the current date, and the minimum year is set to the current year.


protected override void OnNavigatedTo(NavigationEventArgs e)
{
    // Set the default date to 2 months from the current date.
    arrivalDatePicker.Date = DateTimeOffset.Now.AddMonths(2);

    // Set the minimum year to the current year.
    arrivalDatePicker.MinYear = DateTimeOffset.Now;
}

You can format the text in each ComboBox using standard format templates. This example shows how to format the day field to show the day of the month and the abbreviated day of the week. The year field is hidden by setting the YearVisible property to False.


<DatePicker DayFormat="{}{day.integer} ({dayofweek.abbreviated})" YearVisible="False"/>

This example creates this DatePicker.

Date picker with the year hidden

 

The DatePicker also supports vertical layouts by setting its Orientation property. And it's highly customizable: you can use Styles and Templates to customize almost any aspect of the DatePicker and its contents.

Flyout

[Get the XAML Flyout and MenuFlyout sample now.]

Windows 8.1 introduces a new control for XAML that lets you temporarily show UI related to what the user is currently doing: the Flyout control.

A button with a flyout

 

A Flyout displays lightweight UI (called a flyout) that either is informational or requires user interaction. Unlike a dialog, a flyout can be lightly dismissed by clicking or tapping outside it. Use it to collect input from the user, show more details about an item, or ask the user to confirm an action. A flyout should be shown only in response to a user tap or click, and is always dismissed when the user taps outside it.

It’s common to attach a flyout to a button, so the Button control has a new Flyout property to simplify attaching and opening a Flyout control. A flyout attached to a button opens automatically when the button is clicked.

You can also attach a Flyout control to any FrameworkElement object by using the FlyoutBase.AttachedFlyout attached property. If you do so, you must respond to an interaction on the FrameworkElement, such as Tapped, and open the Flyout in your code.

Creating a Flyout

This example creates the Button control with a Flyout that was shown in the preceding illustration.


<Button Content="Empty cart">
    <Button.Flyout>
        <Flyout>
            <StackPanel>
                <TextBlock Style="{StaticResource BasicTextStyle}">All items will be removed. Do you want to continue?</TextBlock>
                <Button Click="DeleteConfirmation_Click">Yes, empty my cart</Button>
            </StackPanel>
        </Flyout>
    </Button.Flyout>
</Button>

The next example shows a Flyout attached to a TextBlock. As noted earlier, you can attach a Flyout to any FrameworkElement by using the FlyoutBase.AttachedFlyout attached property.


<TextBlock Text="{Binding ElementName=MyTextBox, Path=Text}"
           Tapped="TextBlock_Tapped" FontSize="18">
    <FlyoutBase.AttachedFlyout>
        <Flyout>
            <TextBox x:Name="MyTextBox" Text="You can edit this text by tapping it."/>
        </Flyout>
    </FlyoutBase.AttachedFlyout>
</TextBlock>

To open this Flyout, handle the Tapped event and call the FlyoutBase.ShowAttachedFlyout method.


private void TextBlock_Tapped(object sender, TappedRoutedEventArgs e)
{
    FrameworkElement element = sender as FrameworkElement;
    if (element != null)
    {
        FlyoutBase.ShowAttachedFlyout(element);
    }
}

The text block looks like this.

Text with closed flyout

 

When the text block is tapped, the flyout containing the TextBox control opens and the text can be changed.

Text with open flyout

 

You can create a Flyout as a resource and use it on more than one control. Here, a Flyout is defined as a resource and shared between two different controls.


<Page.Resources>
    <Flyout x:Key="SharedFlyout">
        <StackPanel>
            <TextBlock Text="This Flyout is shared."/>                      
        </StackPanel>
    </Flyout>
</Page.Resources>

...

<Button Content="Button" Flyout="{StaticResource SharedFlyout}"/>
<TextBlock Text="TextBlock" FlyoutBase.AttachedFlyout="{StaticResource SharedFlyout}" Tapped="TextBlock_Tapped"/>

To learn more about the Flyout, see Quickstart: Adding a Flyout.

Hub

[Get the XAML Hub control sample now.]

Windows 8.1 introduces a new control for XAML that lets you easily create the hub design pattern that reflects the proper design guidelines and behaviors: the Hub control.

A hub page

 

Hub pages are the user's entry point to your app. They display content in a rich, panning view that lets users get a glimpse of what's new and exciting, and then dig deeper into your app's content. The hub displays different categories of content, each of which maps to your app's section pages. Each section should bubble up content or functionality. The Hub should offer a lot of visual variety, engage users, and draw them in to different parts of the app.

The XAML Hub control provides elements to help you more easily implement the hub design pattern for your app. Unlike a GridView or ListView control that displays data from a single source, each hub section can display data from a different source. Any XAML content can be used to create a visually rich hub page. To get started quickly creating an app with a Hub page, use the Hub App template in Microsoft Visual Studio 2013.

Add a header to the Hub to let users know the context of your hub. This is often the name of your app. You can use a simple text Header, or define a HeaderTemplate that uses any XAML content. It's important to remember that, although you can use arbitrary content in the header, the height of the header will affect the amount of vertical space available for your hub section content. The header remains fixed in position and doesn't scroll with the hub sections.

Hub sections

You put the content of your hub in various HubSection controls. Like the hub, each HubSection has a Header and HeaderTemplate property that you can use to set an optional header for the section. You can also make the section header interactive. Typically, the user can tap an interactive header to go to the corresponding app section page. When its IsHeaderInteractive property is true, the default header includes a chevron glyph, and "Hover" and "Pressed" visual states. If you use a custom HeaderTemplate, provide similar visual cues to indicate that the header is interactive.

You don't add content directly to a hub section; instead, you define the content of your HubSection in a DataTemplate object. Content can either be defined inline or be bound to a data source. Any valid XAML can be used in a hub section.

Creating a Hub

This example shows the basic XAML used to create a Hub control.


<Hub Header="News">
    <HubSection MinWidth="600" Header="Latest">
        <DataTemplate>
            <Grid>   
                <TextBlock Text="The most recent news will be here." 
                           Style="{ThemeResource BodyTextBlockStyle}" />
            </Grid>
        </DataTemplate>
    </HubSection>

    <HubSection Header="Tech" IsHeaderInteractive="True"  
                Background="#222222" MinWidth="250">
        <DataTemplate>
            <StackPanel>
                <TextBlock Text="Tech news goes here."
                           Style="{ThemeResource BodyTextBlockStyle}" />
                <TextBlock Text="Click the header to go to the Tech page."
                           Style="{ThemeResource BodyTextBlockStyle}" />
            </StackPanel>
        </DataTemplate>
    </HubSection>

    <HubSection Header="Sports" IsHeaderInteractive="True" 
                Background="#444444" MinWidth="250">
        <DataTemplate>
            <StackPanel>
                <TextBlock Text="Sports news goes here."
                           Style="{ThemeResource BodyTextBlockStyle}" />
                <TextBlock Text="Click the header to go to the Sports page." 
                           Style="{ThemeResource BodyTextBlockStyle}" />
            </StackPanel>
        </DataTemplate>
    </HubSection>
</Hub>

That example creates this Hub.

A simple hub control

 

Hyperlink

Windows 8.1 adds the Hyperlink element to the XAML text object model in the Windows.UI.Xaml.Documents namespace.

The Hyperlink element lets you add a hyperlink to a run of text. The hyperlink is treated like the rest of the text and participates in line breaking. When marked as a hyperlink, the text is shown in a specific color and, when tapped, goes to the Uniform Resource Identifier (URI) specified in the NavigateUri property.

Here's a block of text with a Hyperlink element embedded in it.

Text with a hyperlink

 

Using a Hyperlink element

This example creates the text shown previously. The Hyperlink flows with the rest of the text, and opens the Windows Dev Center when a user taps it.


<RichTextBlock Width="200" Style="{StaticResource BasicRichTextStyle}">
    <Paragraph>Hyperlinks let you give readers a visual hint that certain text links to other content.
        <Hyperlink NavigateUri="http://dev.windows.com">Read more on the Windows Dev Center</Hyperlink>
        ... Text in a Hyperlink element is treated like the rest of the text and participates in line breaking.
    </Paragraph>
</RichTextBlock>

MenuFlyout

[Get the XAML Flyout and MenuFlyout sample now.]

Windows 8.1 introduces a new control for XAML that lets you temporarily show a list of commands or options related to what the user is currently doing: the MenuFlyout control.

A button with a menu flyout

 

A MenuFlyout displays lightweight UI (called a menu flyout)that is lightly dismissed by clicking or tapping outside it. Use it to let the user choose from a contextual list of simple commands or options. A menu flyout should be shown only in response to a user tap or click, and is always dismissed when the user taps outside it.

You define the contents of the menu by adding MenuFlyoutItem, ToggleMenuFlyoutItem, and MenuFlyoutSeparator objects to the MenuFlyout. These objects are for:

It’s common to attach a menu flyout to a button, so the Button control has a new Flyout property to simplify attaching and opening a MenuFlyout. A menu flyout attached to a button opens automatically when the button is clicked.

You can also attach a MenuFlyout control to any FrameworkElement object by using the FlyoutBase.AttachedFlyout attached property. If you do so, you must respond to an interaction on the FrameworkElement, such as Tapped, and open the MenuFlyout in your code.

Creating a MenuFlyout

This example creates the Button control with a MenuFlyout that was shown in the preceding illustration.


<Button Content="Options">
    <Button.Flyout>
        <MenuFlyout>
            <MenuFlyoutItem Text="Reset" Click="Reset_Click"/>
            <MenuFlyoutSeparator/>
            <ToggleMenuFlyoutItem Text="Shuffle" IsChecked="{Binding IsShuffleEnabled, Mode=TwoWay}"/>
            <ToggleMenuFlyoutItem Text="Repeat" IsChecked="{Binding IsRepeatEnabled, Mode=TwoWay}"/>
        </MenuFlyout>
    </Button.Flyout>
</Button>

SettingsFlyout

[Get the App setting sample now.]

Windows 8.1 introduces a new control for XAML that lets you easily create app settings flyouts that reflect the proper design guidelines and behaviors: the SettingsFlyout control.

The SettingsFlyout

 

Like a Page control, a SettingsFlyout control can be declared in XAML as a root element of a document, with an x:Class attribute specified to subclass from SettingsFlyout. You can set the width of the Settings flyout, but the height is always the full height of the screen.

A SettingsFlyout has a header section and a content section. The header contains a back button, title, and optional icon. Set the HeaderBackground and HeaderForeground to match the colors of your app. By default, the icon shows your app’s small icon. You can specify a different icon by setting the IconSource property. The back button is always visible.

Showing and dismissing the SettingsFlyout

Users can access a Settings flyout through the Settings charm. You can programmatically show a SettingsFlyout control by calling the Show or ShowIndependent method, and dismiss it by calling its Hide method.

By default, the back button dismisses the Settings flyout. If a SettingsFlyout control is shown by calling Show, clicking the back button dismisses the flyout and reopens the settings pane. If a SettingsFlyout is shown by calling ShowIndependent, clicking the back button dismisses the flyout and returns the user to the app. For example, if you open a SettingsFlyout control from a settings button in your app, you will typically call ShowIndependent so users are returned directly to your app when they dismiss the flyout.

Only one SettingsFlyout control can be shown at a time. Calling Show on a SettingsFlyout closes any other SettingsFlyout currently shown.

You can override the default back button behavior by handling the BackClick event. This event is raised whenever the user clicks the back button. To override the default behavior, create an event handler for the event and set the BackClickEventArgs.Handled property to true.

Connecting to the SettingsPane

You must manually associate the SettingsFlyout control with the app’s SettingsPane object. Do this by handling the SettingsPane.CommandsRequested event and adding a SettingsCommand to the ApplicationCommands collection. The SettingsCommand has a label for your SettingsFlyout that’s shown in the Settings charm, and specifies a method that's executed when a user selects the command in the Settings charm. In this method, you create an instance of the SettingsFlyout control and show it.

Creating a SettingsFlyout

Bg182878.wedge(en-us,WIN.10).gifTo add a SettingsFlyout in Visual Studio

  1. Select Project > Add New Item.

  2. In the Add New Item dialog, select Settings Flyout from the middle pane.

  3. Type a name for the Settings flyout file and click Add. In this example, the Settings flyout is named UpdateSettingsFlyout.

    Note  When you add a Settings flyout, you're creating a new class with the name you specify that's derived from SettingsFlyout. To instantiate your Settings flyout, use the name you specified, such as new UpdateSettingsFlyout().

This example creates the SettingsFlyout control shown in the preceding illustration.


<SettingsFlyout
    x:Class="SettingsFlyoutExample.UpdateSettingsFlyout"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:SettingsFlyoutExample"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    IconSource="Assets/SmallLogo.png"
    Title="App Updates"
    d:DesignWidth="346"
    Width="346" 
    HeaderBackground="#FF2B4A80">
    <SettingsFlyout.Resources>
        <Style x:Key="SettingsFlyoutSectionStyle" TargetType="StackPanel">
            <Setter Property="Margin" Value="0,0,0,39"/>
        </Style>
    </SettingsFlyout.Resources>

    <!-- This stack panel acts as a root panel for vertical layout of the content sections. -->
    <StackPanel VerticalAlignment="Stretch" HorizontalAlignment="Stretch" >

        <!-- The stack panels below define individual content sections. -->

        <!-- Content Section 1-->
        <StackPanel Style="{StaticResource SettingsFlyoutSectionStyle}">

            <!-- Section 1 header -->
            <TextBlock Style="{StaticResource TitleTextBlockStyle}"
                                 Text="Automatic updates" />

            <!-- Section 1 body -->
            <TextBlock Style="{StaticResource BodyTextBlockStyle}" Margin="0,0,0,25" TextWrapping="Wrap">
                <TextBlock.Text>
                    Turn automatic updating on or off.
                </TextBlock.Text>
            </TextBlock>
            <ToggleSwitch Header="Download updates automatically" />
            <ToggleSwitch Header="Install updates automatically" />

        </StackPanel>

        <!-- Define more Content Sections below as necessary. -->

    </StackPanel>
</SettingsFlyout>

This example shows how to add the SettingsFlyout to the Settings pane.


public MainPage()
{
    this.InitializeComponent();

    Windows.UI.ApplicationSettings.SettingsPane.GetForCurrentView().CommandsRequested += MainPage_CommandsRequested;
}

void MainPage_CommandsRequested(Windows.UI.ApplicationSettings.SettingsPane sender, Windows.UI.ApplicationSettings.SettingsPaneCommandsRequestedEventArgs args)
{
    Windows.UI.ApplicationSettings.SettingsCommand updateSetting = 
        new Windows.UI.ApplicationSettings.SettingsCommand("AppUpdateSettings", "App updates", (handler) =>
    {
        UpdateSettingsFlyout updatesFlyout = new UpdateSettingsFlyout();
        updatesFlyout.Show();

    });

    args.Request.ApplicationCommands.Add(updateSetting);
}

This example shows how to open the SettingsFlyout from a button in your app.


<Button Content="App update settings" Click="UpdateSettingsButton_Click"/>


private void UpdateSettingsButton_Click(object sender, RoutedEventArgs e)
{
    UpdateSettingsFlyout updatesFlyout = new UpdateSettingsFlyout();
    updatesFlyout.ShowIndependent();
}

TimePicker

[Get the XAML DatePicker and TimePicker controls sample now.]

Windows 8.1 introduces a new control for XAML that lets a user pick a time value in your app: the TimePicker control.

The TimePicker

 

The time picker gives you a standardized way to let users to pick a time using touch, mouse, or keyboard input methods. You can use the TimePicker control in its default form with a minimal amount of XAML or other code, or you can customize it in a variety of ways. The TimePicker can use a 12-hour or 24-hour clock.

Creating a TimePicker

This example shows how to create a simple TimePicker with a header.


<TimePicker x:Name=arrivalTimePicker Header="Arrival Time"/>

This example shows how to create a TimePicker with a 24-hour clock.


<TimePicker ClockIdentifier="24HourClock" Header="24 hour clock"/>

The TimePicker in that example looks like this. The AM/PM selector is automatically hidden.

TimePicker with 24 hour clock

 

You can set the time in code, or bind the control to an instance of a TimeSpan. Here, the TimePicker is set in code to default to 8:00 A.M.


protected override void OnNavigatedTo(NavigationEventArgs e)
{
    // Set the default time to 8 A.M.
    arrivalTimePicker.Time = new TimeSpan(8, 0, 0);
}

You can set the increment in the minute selector to a value that makes sense for your app. Here, the minute increment is 15 minutes.


<TimePicker x:Name=arrivalTimePicker Header="Arrival Time" MinuteIncrement="15"/>

The TimePicker in that example looks like this when the minute selector is opened.

TimePicker with 15 minute increments

 

The TimePicker also supports vertical layouts by setting its Orientation property. And it's highly customizable: you can use Styles and Templates to customize almost any aspect of the TimePicker and its contents.

FlipView updates

[Get the XAML FlipView control sample now.]

The XAML FlipView control supports three modes of navigation: touch-based, button-based, and programmatic. When a user navigates by touch, the FlipView items scroll smoothly into view. However, when navigating by mouse, keyboard, or programmatically, the animation doesn't occur and items simply pop into view. This results in an inconsistent experience across navigation modes.

Windows 8.1 adds the new UseTouchAnimationsForAllNavigation property to the FlipView control to enable a consistent user experience for all navigation modes. When you set this property to true, the same animation occurs whether the navigation is touch-based, button-based, or programmatic.

Headers for ComboBox, DatePicker, TimePicker, Slider, and edit controls

[Get the XAML essential controls sample now.]

Some controls, such as ComboBox, are typically accompanied by a label that describes the control's context. Adding a label to these controls can be inconvenient and requires you to use extra elements, like TextBlock and StackPanel objects, to accomplish the correct layout.

Windows 8.1 adds Header and HeaderTemplate properties to several controls to make it more convenient to label them. These controls have the new properties:

The default Header can't be hit-tested and doesn't accept focus, or mouse or keyboard input. A null or empty string value creates an empty header. An empty header doesn't take up any space or affect layout.

You can use a HeaderTemplate if you need more than a simple text header. A HeaderTemplate can host any valid XAML, including elements that can be hit-tested, like a Button.

Here's how to add a Header to a ComboBox and a PasswordBox.


<ComboBox Header="Colors" PlaceholderText="Pick a color">
    <x:String>Blue</x:String>
    <x:String>Green</x:String>
    <x:String>Red</x:String>
    <x:String>Yellow</x:String>
</ComboBox>
<PasswordBox Header="Password" PlaceholderText="Enter your password"/>

That example creates these controls.

A ComboBox with header

 

A PasswordBox with header

 

In the next example, a HeaderTemplate on a read-only RichEditBox contains a Button control. When the user clicks the button, the rich-edit box becomes editable and the header is changed.


<RichEditBox x:Name="richTextBox1" IsReadOnly="True">
    <RichEditBox.HeaderTemplate>
        <DataTemplate>
            <Button Content="Click to edit" Click="Button_Click"/>
        </DataTemplate>
    </RichEditBox.HeaderTemplate>
</RichEditBox>


private void Button_Click(object sender, RoutedEventArgs e)
{
    richTextBox1.IsReadOnly = false;
    richTextBox1.HeaderTemplate = null;
    richTextBox1.Header = "Editable RichEditBox";
}

That example creates this RichEditBox control.

A RichEditBox with header template

 

When the user clicks the button, the rich-edit box is made editable and the header is changed, like this:

A RichEditBox with header

 

PlaceholderText

Windows 8.1 adds the PlaceholderText property to several controls that contain text. Some controls, such as a ComboBox or PasswordBox, might require user input. When you don't want to assume a default value or show an empty control, you can add placeholder text to provide context for the user.

These controls have the new PlaceholderText property:

On a ComboBox, the placeholder text is shown when the value of SelectedIndex is -1 and the SelectedItem is null. (These two properties are kept in sync.) A user can't display the placeholder text after an item has been selected. However, you can programmatically set either the SelectedIndex to -1 or the SelectedItem to null to cause the placeholder text to be displayed again.

On the text-edit controls, placeholder text is shown when the controls are empty. The user can bring the control back to this state by deleting all text from the controls.

Here's how to add placeholder text to a ComboBox and a PasswordBox.


<ComboBox Header="Colors" PlaceholderText="Pick a color">
    <x:String>Blue</x:String>
    <x:String>Green</x:String>
    <x:String>Red</x:String>
    <x:String>Yellow</x:String>
</ComboBox>
<PasswordBox Header="Password" PlaceholderText="Enter your password"/>

That example creates these controls:

A ComboBox with header

 

A PasswordBox with header

 

WebView updates

[Get the XAML WebView control sample now.]

Windows 8.1 makes it significantly easier to host HTML and web-based content in your apps. In Windows 8.1, the WebView control fixes several issues and adds new functionality, including:

Windows 8.1 deprecates the following WebView API elements:

These changes do not affect Windows 8 apps running on Windows 8.1.

Rendering the XAML tree to a bitmap

The Windows Runtime for Windows 8.1 adds a new type to the Windows.UI.Xaml.Media.Imaging namespace: RenderTargetBitmap.

This type provides two key methods:

  • RenderTargetBitmap.RenderAsync, which takes a XAML visual tree and creates a bitmap representation of it.

    Note  This operation asynchronously renders the given XAML element tree to a bitmap. This method is not synchronized with the screen refresh and does not guarantee exact frame timing, so the bitmap may be rendered a fraction of a second before or after the assumed moment of capture.

  • RenderTargetBitmap.GetPixelsAsync, which returns a byte array of pixels in a specific format.

Here's how to render a XAML element tree.

var renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.RenderAsync(myElementTree);

myImage.Source = renderTargetBitmap;

RenderTargetBitmap inherits from ImageSource, so it can be set directly as the source for an Image object without calling GetPixelsAsync to obtain and display the bitmap data.

Here's how to write the rendered bitmap to a file.

var renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.Render(myElementTree);
var pixels = await renderTargetBitmap.GetPixelsAsync();

var picker = new FileSavePicker();
// Picker setup
var file = await picker.PickSaveFileAsync();
// File validation

using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
    var encoder = await 
        BitmapEncoder.CreateAsync(BitmapEncoder.BmpEncoderId, stream);
    
    encoder.SetPixelData(BitmapPixelFormat.Rgba8, 100, 0, 96, 96,         
        await renderTargetBitmap.GetPixelsAsync());
        
    await encoder.FlushAsync();
}

Other control updates

  • XAML ScrollViewer improvements:

    Windows 8.1 adds ScrollViewer properties (TopHeader, LeftHeader, and TopLeftHeader) that let you define "frozen" areas similar to the frozen panes in Microsoft Excel. These areas contain content that either doesn't scroll or scrolls only in one direction in tandem with the main content. The top left header doesn't scroll, the left header scrolls vertically but not horizontally, and the top header scrolls horizontally but not vertically.

  • XAML data-binding improvements:

    Windows 8.1 adds the following API elements:

  • XAML navigation improvements:

    Windows 8.1 adds the following API elements:

  • Dynamic themes:

    In Windows 8, the light and dark themes for high contrast are loaded when the app starts. But if the user changed the theme while the app was running, the XAML theme system couldn't detect this and the themes wouldn't change in the app. In Windows 8.1, the XAML theme system can detect run-time theme changes and will reload resources. The shared default resources for XAML controls do this automatically in Windows 8.1. To enable this behavior in a custom template that you define yourself, reference the theme-specific resource using the new ThemeResource markup extension. Any resource you define differently on a per-theme basis is then defined in multiple resource dictionaries, one per theme. These resource dictionaries are merged into the overall set of XAML-defined resources for an app. The correct dictionary is loaded dynamically when the system detects a theme change, even if it happens while the app is running.

  • Applying themes on a per-control basis:

    In Windows 8 the theme is set using the Application.RequestedTheme property and applies to all UI in the app. Application.RequestedTheme can't be changed at run-time. In Windows 8.1, you can request that any specific UI element use a theme that's different from whatever Application.RequestedTheme is set to. To do this, you set RequestedTheme as an attribute on the element or elements where you want to use a different theme. This RequestedTheme is a property of the FrameworkElement class and thus exists on basically every UI element. The per-element RequestedTheme value can be set at run-time.

  • GetOpenPopups:

    When you create a XAML Popup control, it doesn't exist in the visual tree. If you want to close pop-ups because of navigation, suspension, or other reasons, and you didn't save a reference, it can be difficult to find and close the Popup elements with Windows 8 code. Windows 8.1 introduces the VisualTreeHelper.GetOpenPopups API so that you have a utility that returns all open pop-ups as a list. You can then set IsOpen to false on any pop-ups you want to close.

  • Accessibility and UI Automation:

    Windows 8.1 adds peers for certain controls that existed in Windows 8 but were using the FrameworkElementAutomationPeer class for support. For example, the AppBar control has a dedicated peer. If you're creating custom peers for classes, you can use these peers as the base and re-use the existing pattern API implementations when implementing your own Microsoft UI Automation peer. There's also managed-code support for the patterns that were added to the overall UI Automation framework for Windows 8. For example, there's an IStylesProvider interface that you can use to implement the Styles pattern on a XAML control peer. Finally there's an app-level AccessibilityView attached property. This can be used to adjust how a given UI element appears in the various UI Automation tree representations that a UI Automation client sees—for example, whether your element appears in the content tree or the control tree.

  • MaxLines property:

    (Applies to TextBlock, RichTextBlock, and RichTextBlockOverflow controls)

    This property lets you specify the maximum number of lines of text shown in a text block. The text control will adjust its height to show no more than the specified number of lines, regardless of the font size, font style, or text length.

  • PreventKeyboardDisplayOnProgrammaticFocus property:

    (Applies to TextBox, RichEditBox, and PasswordBox controls)

    Set this property to true to prevent the onscreen touch keyboard from showing when focus is programmatically set on a text box. By default, the touch keyboard is displayed whenever focus moves to an editable text box and the most recent input was generated by touch. This happens whether focus is set programmatically or by user interaction. In some situations, you might not want the keyboard to appear when focus is set programmatically. For example, you might want to prevent the keyboard from covering part of your UI until the user is ready to continue an interaction.

  • SelectionHighlightColor property:

    (Applies to TextBlock, TextBox, RichEditBox, RichTextBlock, and PasswordBox controls)

    You can specify a SolidColorBrush to change a text control's highlight color to match your app's branding.

  • Paste event:

    (Applies to TextBox, RichEditBox, and PasswordBox controls)

    You can provide custom handling of the Paste event on editable text controls in your app.

  • TextWrapping.WrapWithOverflow value:

    Use this value when you don't want wrapping to occur in the middle of a word. The last word will overflow the text block rather than wrap.

    With this value, line-breaking occurs if the line overflows beyond the available block width. However, a line may overflow beyond the block width if the line-breaking algorithm cannot determine a line-break opportunity, as in the case of a very long word that's constrained in a fixed-width container with no scrolling allowed.

  • TextTrimming.Clip value:

    With this value, text is trimmed at a pixel level, visually clipping the excess glyphs.

  • TextTrimming.CharacterEllipsis value:

    With this value, text is trimmed at a character boundary, rather than at a word boundary. An ellipsis ("...") is drawn in place of the remaining text.

 

 

Show:
© 2014 Microsoft