Windows ui xaml controls

Provide feedback

Saved searches

Use saved searches to filter your results more quickly

Sign up

Appearance settings

This post was written by Rohan Thakkar, Program Manager 2 – Developer Ecosystem Platform on Operating Systems Group at Microsoft.

At //build 2014 we introduced the ability to build universal Windows apps, which are able to share a large amount of code between Windows 8.1 and Windows Phone 8.1 projects. In particular, three sessions at //build discussed the important features for developers working with XAML:

  • What about XAML UI and Controls? by Shawn Oster
  • Quality and Performance for XAML Apps by Stefan Wick
  • Animations in Windows Phone XAML Apps by Kunal Deep Singh and Rohan Thakkar

To follow up from those talks, we wanted to share with you the golflink sample app used for our demos and use it as a basis to share a number of tips and tricks for working with XAML controls in universal apps. For more background on XAML basics, refer to Create your first Windows Runtime app using C# or Visual Basic, Creating a UI (XAML), and Developing apps (XAML) in the documentation.

Adaptive UI

Sharing common pages

When sharing a page across Windows and Windows Phone projects, the first thing you must tackle is to ensure Windows has a software back button for in-app navigation and Windows Phone has a hardware back button for in-app navigation. The sample demonstrates a CommonPage.XAML and how to tackle the back button problem. We have done this using a separate user control, PageTitleUserControl.xaml, for Windows and Windows Phone that will be instantiated from the CommonPage in the shared project. You need to pass in a reference to the NavigationHelper for the back navigation.

public CommonPage()
{
this.InitializeComponent();
this.navigationHelper = new NavigationHelper(this);
this.InsertPageTitleUserControl();

this.navigationHelper.LoadState += navigationHelper_LoadState;
this.navigationHelper.SaveState += navigationHelper_SaveState;
}
private void InsertPageTitleUserControl()

    PageTitleUserControl pageTitle = new PageTitleUserControl(this.navigationHelper);
    pageTitle.PageTitle = "Common page";
    pageTitle.AppName = "APP NAME";
    rootGrid.Children.Add(pageTitle);
    Grid.SetRow(pageTitle, 0);
}

Sharing UserControls

UserControls can be different, like in the above sample, but be used in a shared page. The best and most common use is to have bunch of shared UserControls (think fragmentsJ) for common parts of the UI and use them for respective XAML pages (views). In the golflink sample, we could have used them more heavily. However, to demonstrate their usefulness, check out the SharedUserControlsProfileControl.xaml and its usage in HubPage.XAML.

Sharing Styles

Sometimes you have unique styles for respective frameworks and share them. This is a nice trick that can be very handy.

In golflink sample, WindowsStylesStyles.xaml has a resource dictionary with a set of unique styles that exist by default on Windows Phone 8.1’s generic.xaml. These styles (and maybe others) must be defined for Windows projects to be able to share the XAML with phone. Let us take a look at our example.

WindowsStylesStyles.xaml

<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:golflink.Styles">

<Style TargetType="TextBlock" x:Key="ListViewItemSubheaderTextBlockStyle">
<Setter Property="FontSize" Value="15"/>
<Setter Property="Margin" Value="0,6,0,0"/>
</Style>
<Style TargetType="TextBlock" x:Key="ListViewItemContentTextBlockStyle"/>
<Style TargetType="TextBlock" x:Key="ListViewItemTextBlockStyle"/> 
<SolidColorBrush Color="Blue" x:Key="PhoneAccentBrush"/>
<SolidColorBrush Color="White" x:Key="PhoneForegroundBrush"/>
<x:Double x:Key="ContentControlFontSize">20.26</x:Double>
</ResourceDictionary>

ListViewItemSubHeaderTextBoxStyle does not currently exist on Windows 8.1 but it does on Phone 8.1. We define it here.

Similarly on the phone side we might require a style with a key shared with Windows to behave differently. We put it under PhoneStylesStyles.xaml.

Now, as you might imagine, these were styles unique to each project. The styles that are common to both projects are in shared project’s app.xaml (SharedApp.xaml).

Here, you will also merge the Styles.xaml’s resource dictionary using the highlighted mark up:

<Application
x:Class="golflink.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:golflink"
xmlns:localData="using:Shared">

<Application.Resources>
<!-- Application-specific resources -->
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/Styles/Styles.xaml"/>
</ResourceDictionary.MergedDictionaries>
<x:Double x:Key="largeCellHeightPercent">0.392</x:Double>
<x:Double x:Key="largeCellWidthPercent">0.392</x:Double>


<x:Double x:Key="mediumCellHeightPercent">0.205</x:Double>
<x:Double x:Key="mediumCellWidthPercent">0.205</x:Double>

<x:Double x:Key="smallCellHeightPercent">0.138</x:Double>
<x:Double x:Key="smallCellWidthPercent">0.138</x:Double>
</ResourceDictionary>
</Application.Resources>
</Application>

The end result is a nice way to merge dictionaries and share styles where appropriate.

Window-based width adaption

Sometimes you want to set the width of certain controls to be relative to the window size (or dimensions of the device). For example, on phone, a HubSections width should ideally be 90% of window width. The percentage-based dimensions can be handy at many places, and here we describe simple steps on how to achieve the goal using behaviors. An important note here is that one might get carried away and use percentage-based width/height everywhere, but you should step back and realize the need for it. Existing layout primitives like Grid/StackPanel coupled with alignment properties provide a pretty powerful adaptive UI mechanism. So, the take away is use WindowDimensionBehavior for percentage-based widths only when you absolutely cannot use Grid/StackPanel. Here is how you would do it:

Step 1. Add Behaviors SDK. Right-click both projects Windows/Windows Phone individually and add reference. Select Extensions SDK -> Behaviors SDK.

add_behaviors

reference_manager

Step 2. Create a shared Helper class, WindowDimensionBehavior.cs:

using Microsoft.XAML.Interactivity;
using Windows.UI.XAML;
using Windows.UI.XAML.Controls;

namespace golflink.Helpers
{

    [Microsoft.XAML.Interactivity.TypeConstraint(typeof(FrameworkElement))]
class WindowDimensionBehavior : DependencyObject, IBehavior
    {
public WindowDimensionBehavior()
        {
this.WidthMultiple = 1;
this.HeightMultiple = 1;
this.HeightPercentage = double.NaN;
this.WidthPercentage = double.NaN;
        }
public DependencyObject AssociatedObject { get; set; }            

public FrameworkElement TypedObject { get; set; }
public int WidthMultiple { get; set; }

public double WidthPercentage { get; set; }

public int HeightMultiple { get; set; }

public double HeightPercentage { get; set; }

public void Attach(DependencyObject associatedObject)
        {
this.AssociatedObject = this.TypedObject = associatedObject as FrameworkElement;

this.TypedObject.Loaded += TypedObject_Loaded;
            Window.Current.SizeChanged +=Current_SizeChanged;

        }

void TypedObject_Loaded(object sender, RoutedEventArgs e)
        {           
            Handle();
        }

void Current_SizeChanged(object sender, Windows.UI.Core.WindowSizeChangedEventArgs e)
        {
            Handle();
        }

private void Handle()
        {
            var frameWorkElement = (this.TypedObject as FrameworkElement);

//I base all the percentage calculations on shortest dimension, you can modify this depending on your layouts requirements.
double shortestDimension = (Window.Current.Bounds.Width <= Window.Current.Bounds.Height) ? 
                Window.Current.Bounds.Width : Window.Current.Bounds.Height;

if (frameWorkElement != null)
            {
if(this.WidthPercentage!=double.NaN)
                frameWorkElement.Width = shortestDimension * this.WidthPercentage * this.WidthMultiple;                
if(this.HeightPercentage!=double.NaN)
                frameWorkElement.Height = shortestDimension * this.HeightPercentage * this.HeightMultiple;
            }
        }

public void Detach()
        {
            Window.Current.SizeChanged -= Current_SizeChanged;
            (this.AssociatedObject as Control).Loaded -= TypedObject_Loaded;

        }
    }
}

Step 3. Use it in XAML

Don’t forget to add xmlns reference:

xmlns:Interactivity="using:Microsoft.XAML.Interactivity"

Then in the actual Hub section where you want to make the width twice of 90% of the window width:

<HubSection  x:Uid="Section2Header" Header="MY GAME" DataContext="{Binding Profile}">
<Interactivity:Interaction.Behaviors>
<helpers:WindowDimensionBehavior WidthMultiple="2" WidthPercentage="0.9"/>
</Interactivity:Interaction.Behaviors>
<DataTemplate>

And use it responsibly.

Revisiting the goodness of layout primitives (Grid/StackPanel)

The WindowsPlayers.xaml page makes almost no use of the WindowDimensionBehavior mentioned above. 99% of the layout is done using basic layout primitives like Grid, StackPanel, ListView and GridView. Make good use of the HorizontalAlignment/VerticalAlignment and HorizontalContentAlignment/VerticalContentAlignment properties coupled with the magic of Grid’s “star” capabilities.

On the other hand, on the Phone’s Players.xaml page, we have extensively used behaviors (not recommended, but left there for comparison).

Viewbox

This can be handy at times when you want the text font to scale with window dimension. We used it in a couple of places in the project (an exercise for you to search and learn why; let us know if you think of other ways to achieve the same desired scenario). Just knowing that this control exists for your layout magic is super useful.

VisualStateManager

Use it along with the Window_SizeChanged event to swap out item templates or show/hide different controls on your layout. Unfortunately, we haven’t used it in our demo app. However, there is nothing new or fancy here to demonstrate. XAML experts know the power of VSM. Folks who are not familiar with VSM can take a look at Quickstart: Designing apps for different window sizes.

Test test test…

Universal apps will have a massively diverse dimensional reach. It is very important to test your app’s layouts in different resolutions and dimensions. Remember, width is not the only thing that varies. Height also varies significantly. An easy way to test is using Simulator for Windows and Emulator for phone or the designer.

golflink

The Golflink app has bugs; we could not fix all of them. Curious readers can try and see which layouts have problems.

Specific common controls but different behaviors

Hub

Windows Store Apps using XAML Hub share the same API as Windows Hub, but it looks and feels like the Phone 8.0 Panorama. When authoring an app using Phone Hub here are a few things to note or do differently.

  • HubSection’s width is by default set to 90% of window width. If the content of the section is wider than this, it will get clipped.
  • If you want the HubSection to expand to match the width of the content, you need to set the width of HubSection to Auto
    <HubSection Width="Auto"/>
  • The recommended way to have a wide HubSection is to make the section’s width equal to a multiple of 90% of the window width. There are different ways to achieve this. In the sample we have used behaviors (recommendation from Jerry Nixon, thanks!) and shared a behavior class to achieve this. Check the adaptive UI section for step-by-step instructions on how to use WindowDimensionBehavior.cs.

  • Use the Hub.SectionsInViewChanged event to identify SectionsInView. This is a replacement for the 8.0 Panorama.SelectionChanged event and SelectedIndex. In the golflink sample we have used it to show/hide app bar for “recent” section.
  • Hub is designed to be used with Orientation=”horizontal” ONLY. Do not use it in Orientation=”vertical”.
private void Hub_SectionsInViewChanged(object sender, SectionsInViewChangedEventArgs e)
{
if(Hub.SectionsInView!=null && Hub.SectionsInView.Count>0)
if(Hub.SectionsInView[0].Name=="recent")
    {
        appBar.ClosedDisplayMode = AppBarClosedDisplayMode.Compact;
        (appBar.PrimaryCommands[0] as AppBarButton).Visibility = Windows.UI.XAML.Visibility.Visible;
    }
else
    {
        appBar.ClosedDisplayMode = AppBarClosedDisplayMode.Minimal;
        (appBar.PrimaryCommands[0] as AppBarButton).Visibility = Windows.UI.XAML.Visibility.Collapsed;
    }
}

Tip: Two section Hubs don’t wrap. This is by design. Having a Hub with fewer than three sections is not recommended UX and supporting wrapping for two section Hubs was very expensive.

SemanticZoom

SemanticZoom is available on both platforms but the interaction model varies significantly.

Windows behavior

It is the same as you know on Windows 8.1. You pinch on the ListView/GridView within a SemanticZoom to get the zoomed out view. Our sample uses SemanticZoom in Players.XAML

players_groups

After you pinch the contacts you get the ZoomedOut view:

players_groups_zoom

Windows Phone behavior

In the phone world, this used to be referred to as a JumpList in LongListSelector, and you invoke it by tapping on the group headers. Interaction for it stays the same. When the user taps the group header, SemanticZoom.ZoomedOutView is invoked with an animation similar to native phone jumplists. Here is an image to remind you what we are talking about. A sample for this is available in golflink.Phone project’s Players.xaml “all” players pivot item. Justification for the divergent interaction model has been that tablets are two-handed devices where the device is held with one hand and the screen is pinched with the other whereas phones are one-handed devices, and to invoke the zoomed out view (jump list) you only need to tap on the group header.

Tip: For the Listview on Windows Phone 8.1 XAML, do not forget to add a width to the ListView item template to avoid a horizontal bouncing bug. Check the sample comments in Players.XAML

DatePicker/TimePicker

DatePicker and TimePicker APIs are both available on the Windows 8.1 and Windows Phone 8.1 XAML stack, but they look and interact differently. Settings.XAML includes a basic sample. Here are a few screenshots.

Windows behavior

Windows Phone behavior

ComboBox

Windows behavior

Windows Phone behavior

The Phone ComboBox item list expands in place when there are up to five items, but will turn into a picker flyout for more than five items.

MenuFlyout

Similar to DatePicker/TimePicker. The experience for MenuFlyout is unique to each OS. The sample is in Settings.XAML page.

Windows behavior

On Windows it’s a simple flyout with menu items.

simple_data_picker

Windows Phone behavior

Windows Phone has an “elevator/escalator” animation (similar to ContextMenu from WPToolkit).

Phone-only control APIs

There are a few controls that we added after Windows 8.1 shipped that are only a part of the Windows Phone 8.1 stack (for now, yes, we understand and feel the pain of divergence).

Listview/Gridview additional properties

Converters for zoomed out view (jumplist)

JumpListItemBackgroundConverter/JumpListItemForegroundConverter helps with setting the right colors for the Jumplist (zoomed out semantic zoom view). Used in Player.xaml’s “all” pivot item.

ReorderMode

It is very easy to invoke reorder mode now. All you need is a two-way binding with the collection on your ListView and then Enable/Disable this property on the ListView. You will see the usage on Windows Phone’s Players.xaml page (“favorites” pivot item).

However, there is no ReorderMode_changed event, so you need to use data binding to get the state changes of ReorderMode. Here is how we have done it in the app:

Players.xaml

<Page
x:Class="golflink.Pages.Players"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:golflink.Pages"    
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:prim="using:Windows.UI.XAML.Controls.Primitives"
xmlns:Interactivity="using:Microsoft.XAML.Interactivity" 
xmlns:helpers="using:golflink.Helpers"
mc:Ignorable="d" Name="rootPage">
<ListView Name="favoritesListView" ItemsSource="{Binding RecentPlayers}" 
ReorderMode="{Binding ReorderMode, ElementName=rootPage, Mode=TwoWay}"
ItemTemplate="{StaticResource RecentListViewItemTemplate}">
</ListView>

Players.xaml.cs code behind

public sealed partial class Players : Page, INotifyPropertyChanged
{
//other usual methods

private void editAppBarButton_Click(object sender, RoutedEventArgs e)
    {
this.ReorderMode = ListViewReorderMode.Enabled;
        ReorderModeChanged();
    }

private void acceptAppBarButton_Click(object sender, RoutedEventArgs e)
    {
this.ReorderMode = ListViewReorderMode.Disabled;
        ReorderModeChanged();
    }

private void ReorderModeChanged()
    {
if(this.ReorderMode == ListViewReorderMode.Enabled)
        {
            playerPivot.IsLocked = true;//lock the pivot
            editAppBarButton.Visibility = Windows.UI.XAML.Visibility.Collapsed;
            acceptAppBarButton.Visibility = Windows.UI.XAML.Visibility.Visible;   
        }
else
        {
            playerPivot.IsLocked = false;
            editAppBarButton.Visibility = Windows.UI.XAML.Visibility.Visible;
            acceptAppBarButton.Visibility = Windows.UI.XAML.Visibility.Collapsed;
        }
    }

private ListViewReorderMode _reorderMode = ListViewReorderMode.Disabled;
public ListViewReorderMode ReorderMode
    {
        get
        {
return _reorderMode;
        }
        set
        {
if (_reorderMode != value)
            {
                _reorderMode = value;
                NotifyPropertyChanged();
this.ReorderModeChanged();
            }
        }
    }

public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
    {
        PropertyChangedEventHandler handler = PropertyChanged;
if (null != handler)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

Pivot

Pivot for Windows Phone 8.1 XAML shares the same behavior as Windows Phone 8.0, but the API is not available in Windows 8.1 XAML. This makes it tricky to share the page across the two projects in universal apps.

In our example, we have two separate XAML files. The Phone side uses the Pivot and the Windows side uses a custom design implementation that suits the app’s content.

The Pivot API in Windows Phone 8.1 XAML SDK is same as the Silverlight 8.0 Pivot API. One delightful feature that was included was Pivot.SlideInAnimationGroup=”GroupOne”. The intent of this property is to slide in FrameworkElements when the selected PivotItem changes. All the elements in a group slide in together and you can have three different levels (groups). Use it responsibly. Check out Phone’s Players.xaml for the usage example.

StatusBar, margins on pages and headers

StatusBar (System tray) is now always visible on Windows Phone 8.1 unless explicitly hidden. Its opacity is set to 0. To explain this part, let us define CoreWindowBounds as the screen window, the size of the phone window in logical pixels. VisibleBounds is the size of the visible region of the window (CoreWindowBounds minus size of StatusBar+AppBar).

By default, the page’s content takes the VisibleBounds, however the page background, when set, takes the CoreWindowBounds. If you set a background on the page, it goes all the way from top to bottom, behind the app bar and status bar. But the content of the page stays in the visible region.

To be clear, let’s look at the basic XAML below:

<Page
x:Class="App29.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App29"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="Red">

<Grid Background="Yellow">

</Grid>
<Page.BottomAppBar>
<CommandBar Name="appBar" Visibility="Visible" Opacity="0.5">
<CommandBar.PrimaryCommands>
<AppBarButton Icon="Edit"
Label="edit" Name="editAppBarButton"/> 
</CommandBar.PrimaryCommands>
</CommandBar>
</Page.BottomAppBar>
</Page>

This is the result of the page:

This is good. Now you don’t need to worry about the content of the page being occluded by either StatusBar or AppBar.

Additionally, Pivot/Hub templates already offset their respective headers to account for a visible/hidden StatusBar, so you don’t need to worry about it.

Tip: You should be careful when toggling the state of the appbar’s ClosedDisplayMode as it resizes the content and could result in the page jumping. We recommend toggling the state of the appbar only when you have a ScrollViewer on that particular page (or HubSection or PivotItem).

Then, unfortunately, one of the scenarios was not caught earlier. It is better that we list the workaround here than to have you go through an ordeal trying to fix the issue.

If you have a Jumplist (SemanticZoom) as a child of a PivotItem/HubSection, the transition is not smooth from the ZoomedOut to ZoomedIn view because of this margin adjustment and because the Jumplist hides the StatusBar automatically. The workaround here is to disable the page resizing. It is important to note that this is a global, app-wide setting. So don’t forget to re-enable VisibleWindow when you leave the page.

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    navigationHelper.OnNavigatedTo(e);
    (Windows.UI.ViewManagement.ApplicationView.GetForCurrentView()).
SetDesiredBoundsMode(Windows.UI.ViewManagement.ApplicationViewBoundsMode.UseCoreWindow);
}

protected override void OnNavigatedFrom(NavigationEventArgs e)
{
    (Windows.UI.ViewManagement.ApplicationView.GetForCurrentView()).
SetDesiredBoundsMode(Windows.UI.ViewManagement.ApplicationViewBoundsMode.UseVisible);
    navigationHelper.OnNavigatedFrom(e);
}

The PivotHeaders are fine and in place. All you need to do is ensure your content is not occluded by the AppBar (CommandBar). Add compensation padding at the end of the content to account for the app bar. In our case, we do it using the footer property on ListView:

<ListView.FooterTemplate>
<DataTemplate>
<Rectangle Fill="Transparent" Height="60"/>
</DataTemplate>
</ListView.FooterTemplate>

ContentDialog

This is a custom message dialog with phone dialog UX that is completely customizable. You can also cancel the closing of the dialog if the result of the dialog is not to your app’s liking (example terms and conditions are not accepted).

A basic sample can be found on settings.xaml page for phone project.

AutoSuggestBox

The Windows 8.1 functionality equivalent for this would be SearchBox, which allows you to do suggestions. AutoSuggestBox is lightweight, without Search integration, and suggestions in a list with ItemsControl. A sample can be found on Settings.xaml page for phone.

ListPickerFlyout

Unique to Windows Phone, you can now have ListPickerFlyouts to display a list of content in a pop-up-like fullscreen window. Sample usage in Settings.xaml of phone project

Animations

The talk on animation at //build pretty much covered everything. The sample demonstrates the usage from the talk. Here is a brief summary:

  • All the animations existing on Windows also exist on Phone. Some might be modified for phone UX (for example, PointerDownThemeAnimation is more like the tilt effect on phone; refer to the Profile.xaml usercontrol sample).
  • Phone has added a new concept of NavigationThemeTransitions on pages. There are three different types of navigation animations: CommonNavigationTransitionInfo (default turnstile animation), SlideInNavigationTransitionInfo and ContinuumNavigationTransitionInfo. These are all covered in the animations talk and used in the sample. This could be a differentiating factor between a four star and a five star app. For more details refer to Kunal’s talk from Build – Animations in Windows Phone XAML Apps
  • Here is an example of how to define it:
    <Page.Transitions>
    <TransitionCollection>
    <NavigationThemeTransition>
    <NavigationThemeTransition.DefaultNavigationTransitionInfo>
    <CommonNavigationTransitionInfoSlideNavigationTransitionInfo/>
    </NavigationThemeTransition.DefaultNavigationTransitionInfo>
    </NavigationThemeTransition>
    </TransitionCollection>
    </Page.Transitions>

When going from page A to page B, the framework plays the animation as defined on page B. And then, when navigating back from page B to page A, the framework will play the right animation contextual to the navigation (example – in this case slide-out page B).

slide_out

XAMLToolkit

Almost everything that was in WPToolkit is now part of the Universal XAML framework. What are you looking for in XAMLToolkit? We really want to know. Your feedback helps us prioritize the work we do.

Conclusion

Phew. . . that was a lot of content. We have worked really hard to provide this level of convergence in universal apps. We know it is not 100% perfect but it’s a step in the right direction. We hope this post helped you get past a few glitches you might have encountered when writing your universal app.

Thank you for reading this far and feel free to reach out with questions in comments or directly

User interface is the part of an app that user directly access and interact with it. So, while developing any project developer needs to ensure that it has very attractive and efficient user interface.

I window store apps there are so many feature are available for creating a very attractive user interface. Like UI elements, flyouts, styles and animations etc.

Adding UI elements to an Interface

To design the Interface of an app we need to add various UI(User Interface) elements to the app. In windows store app adding UI elements to an interface there are two ways available:

At the design time

At the designing time we can add UI elements using XAML code. This we can accomplish using two ways:

      By writing the XAML code for the control in text editor.

      By dragging the controls from toolbox onto the design surface using IDE.

At the run time

At the run time we can add UI elements using C# along with XAML code.

Controls in Windows store app

Text Controls:

These controls are used to accept text from user or If we want to display some text in form of Lables to user. Text controls are further classified in following types.

TextBox:

This control is used to accept data from user in the form of single line or multiline text input.

<TextBox><TextBox/> tag is used in XAML code. We can also customize the textbox and style of thex by using various properties of TextBox control.

  • Property
  • Description
  • Text

Used to set or retrieve the contents of textbox as string

  • Height

Used to set or retrieve the height of textbox.

  • Width

Used to set or retrieve the width of textbox.

  • Foreground

Used to set the color of content of textbox.

  • TextWrapping

Used to set the breaking of line of text. Possible values are Wrap/NoWrap. By default is Wrap

  • AcceptReturn

Used to get or set a value that determines whether the textbox move to the next line by pressing Enter key or not. Possible values are True/False.By default is False.

  • IsSpellCheckEnabled

Used to enable or disable the spell check feature in TextBox.Possible values are True/False. By default is False.

  • IsReadOnly

Used to enable or disable the editing of the TextBox. Possible values are True/False. By default is False.

To add a multiline text box in window store app, we need to set theTextWrapping property as Wrap and the AcceptReturn property as True.

TextBlock:

This control is used to display non editable text or label element in our app. Use <TextBlock> tag in XAML to add TextBlock control.

  • Property
  • Description
  • Text

Used to set or retrieve the contents of text block

  • Visibility

Used to set the visibility of text block. Possible values are Visible/Collapsed. By default the value is Visible.

  • FontFamily

Used to set the font family of contents.

  • FontSize

Used to set the font size in pixels.

  • Foreground

Used to set the color of content.

  • HorizontalAlignment

Used to set the horizontal alignment of text block.

  • Margin

Used to set the outer margin of the text block from left, top, right and bottom.

  • VerticalAlignment

Used to set the vertical alignment of the text block.

  • x:Name

Used to assign a unique name to the text block.

PasswordBox

  • Property
  • Description
  • PasswordChar

Used to set or retrieve the characters in place of original text.

  • MaxLength

Used to set or retrieve the maximum number of characters that can enter in box.

  • Password

Used to set or get string as password.

  • IsPasswordRevealButtonEnabled

Used to enable or disable the visibility of the reveal button in the password box.

Buttons

Property Description
IsEnabled Used to get or set a value that decides the user can interact with the button or not.
Background Used to get or set background color for the button
FontSize Used to set the size of text.
Height Used to set or get the height of button
Style Used to get or set an inbuilt or custom style for the button
Content Used to get or set the text that will appear on button

App Bars

This is the new feature of Windows 8. It supports content before chrome feature. By default it is hidden and displayed whenever required. It can be add in application by using AppBar control.

Property Description
VerticalAlignment Used to set the vertical alignment of the app bar. Possible values are Bottom, Center, Stretch and Top
HorizontalAlignment Used to specify the horizontal alignment of the app bar.
IsOpen Used to set or get a value that indicates whether the app bar is visible.

Images and Shapes

To display images in app, Image control can be used. The source image should be kept in root folder or in Assets folder of the project.

Property Description
Source Used to get or set the location of image source file.
Height Used to get or set the height of the image.
Width Used to get or set the width of the image.
Opacity Used to get or set the degree of visibility of the image.

Shape

To draw shapes in app. We can use <Rectangle></Rectangle> or <Ellipse></Ellipse> control in app.

Property Description
Fill Used to get or set color or gradient foe the interior of the shape
Height Used to get or set the height of shape
Width Used to get or set the width of shape
Margin Used to set or get the outer margin of the shape.

Collection/Data Controls:

These controls are used to display a set of data items in an app. These are of following types:

Flip view:

This control displays one item at a time and user can flip between the items of collection. <FlipView> control can be used for this.

Property Description
HorizontalAlignment Used to get or set the horizontal alignment of the flip view. Possible values are Left, Center, Right or Stretch.
VerticalAlignment Used to get or set the vertical alignment of the flip view. Possible values are Top, Center, Bottom or Stretch.

Grid view

This control is used to add a collection of items in the form of grid. <Grid> control is used in XAML to add this control.

Property Description
Margin Used to get or set the outer margin of the grid.
SelectionMode Used to get or set the way items can be selected in the grid view. Possible values are Extended, Multiple, None and Single.
VerticalAlignment Used to get or set the vertical alignment of grid control

List view

This control is used to add  a list of items in app that can be scrolled vertically.

Property Description
Margin Used to get or set the outer margin of the list view.
SelectionMode Used to get or set the way items can be selected in the list view. A user can select one or more items by setting the value of SelectionMode property. Possible values are Single, Multiple or Extended.

Semantic zoom

This control is used to zoom between two views of the same content. For this Semantic Zoom control uses two controls, one that provides the zoomed in view and the other provides zoomed out view. Firstly we use <SemanticZoom> </SemanticZoom> control, then we add <SemanticZoom.ZoomedInView /> and <SemanticZoom.ZoomedOutView /> controls.

Property Description
ZoomedOutView Used to get or set the zoomed out view of this control
ZoomedInView Used to get or set the zoomed in view of this control.
IsZoomedInViewActive Used to get or set a value that decides whether the zoomed in view is active view.
IsZoomOutButtonEnabled Used to get or set a value that decides whether a button is present in zoomed in view that switches user to zoomed out view.

Selection Controls

These controls provide the way of selection controls in which user select multiple options.

Radio button

This control allows user to create a set of options from which user can choose only one option.

Property Description
Content Used to get or set the text displayed with radio button.
IsChecked Used to determine whether the radio button is selected.
GroupName Used to get or set the name of group of radio button.

Check box

User can choose multiple options from a group of options.

Property Description
Content Used to get or set the text displayed along with check box.
IsChecked Used to determine whether the checkbox is selected or not.
Combo box  
Property Description

List box

This control is used to display a list of items from which a user can select one or more items.

Property Description
SelectionMode Used to get or set whether a single option or multiple options can be selected. Possible values are Single, Multiple or extended.
SelectedIndex Used to get or set the index of the selected item
SelectedItems Used to get the list of selected items.

Slider

This control is used to select a value from a continuous range of values. User can select a value by pointing along a track.

Property Description
Value Used to get or set the current value on the slider
Maximum Used to get or set the maximum value present on slider range. By default the value is 100
Orientation Used to get or set the orientation of slider control. Possible values are horizontal and vertical. By default it is horizontal.

Toggle button

This control represents a button that can be switched between two states.

Property Description
Content Used to get or set the caption of toggle button
IsChecked Used to get or set a value that decides whether the toggle button is selected or not.

Toggle switch

This control represents a switch button that can be toggled between two stages.

Property Description
Header Used to get or set the title of toggle switch
IsOn Used to get or set the value that decides whether the toggle switch is on or off.
OnContent Used to get or set the text to be displayed on On state
OffContent Used to get or set the text to be displayed on Off state

Media Controls

These controls are used to include audio and video in app

Property Description
Source Used to get or set the path of the media
Volume Used to get or set the volume of the media
Position Used to get or set the position upto which media has been played.
AutoPlay Used to get or set whether the media will be start auto playing.
NaturalDuration Used to get or set the duration or length of the currently opened media file.
IsLooping Used to get or set the property by which media will be played in a loop.
PosterSource Used to get or set the source of an image that can be displayed when media is loading or playing.

Navigation Controls

These controls are used to navigate from one page to another page or window of an app.

HyperLink Button

This control is used to add a hyperlink to app. Using this link a user can navigate to another location, it can be a file or web location.

Property Description
Content Used to get or set the text that appear on the hyperlink.
NavigateUri Used to get or set the Unique Resource Identifier of file location.

Progress Controls

These controls are used to represent the progress of an operation that takes more than 2 seconds to complete.

ProgressBar

It indicates the progress of an operation by displaying a bar. It can be determinate or indeterminate progress. The determinate progress shows percentage of the completion of an operation, Indeterminate shows only that the operation is in progress.

Property Description
IsIndeterminate Used to get or set a value specifies whether the progress bar is determinate or Indeterminate
Maximum Used to get or set the highest possible value of progress.
Value Used to get or set the current value of progress

ProgressRing

This control is used to indicate the indeterminate progress by displaying a ring.

Property Description
IsActive Used to get or set a value that specifies whether the progress ring is functioned or not.
Foreground Used to get or set a solid color or gradient for the progress ring.

Demonstration

We have to create Music Player App , which should has following Interface:

          

For this we can use various UI elements of XAML like:

After the completion of adding elements in User Interface, following Interface will be created:

          

For this we have to use following steps:

  • Create a blank Windows store app.
  • Design the playlist
  • Add media control
  • Add player button
  • Add volume control
  • Add slider
  • Verify the app

For this we have to create XAML application like this:

MusicPlayer.xaml file

<Page
    x:Class="MusicPlayer.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:MusicPlayer"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">
    <Grid HorizontalAlignment="Center" VerticalAlignment="Center">
        <Viewbox>
            <Grid x:Name="grdMusicPlayer" Background="Black">
                <Button Content="PlayList" HorizontalAlignment="Left" Margin="7,55,0,0" VerticalAlignment="Top" Background="CadetBlue" Width="360" Height="53" FontSize="24" BorderThickness="0"/>
                <ListBox FontSize="22" x:Name="lstViewPlayList" HorizontalAlignment="Left" Height="642" Margin="10,105,0,0" VerticalAlignment="Top" Width="355" BorderBrush="Blue" BorderThickness="1" ScrollViewer.VerticalScrollBarVisibility="Auto" ScrollViewer.HorizontalScrollBarVisibility="Auto"/>
                <Grid HorizontalAlignment="Left" Height="454" Margin="391,58,0,0" VerticalAlignment="top" Width="948">
                    <Border BorderBrush="White" BorderThickness="3">
                        <MediaElement x:Name="mediaSource" AutoPlay="False" Height="Auto" Width="Auto" Margin="0,4,0,-4"/>
                    </Border>
                </Grid>
                <Button x:Name="bttnPlay" Margin="807,662,0,21" Visibility="Visible" Content="&#xE102;" FontFamily="Seoge UI Symbol">
                </Button>
                <Button x:Name="bttnPause" Visibility="Collapsed" Margin="807,662,0,21" Content="&#xE103;" FontFamily="Seoge UI Symbol">
                </Button>
                <Button x:Name="bttnPrevious" Margin="696,662,0,21" Content="&#xE112;" FontFamily="Seoge UI Symbol">
                </Button>
                <Button x:Name="bttnNext" Margin="971,662,0,21" Content="&#xE111;" FontFamily="Seoge UI Symbol">
                </Button>
                <ToggleSwitch x:Name="tglSwitchMediaRepeat" Header="" HorizontalAlignment="Left" Margin="392,678,0,0" VerticalAlignment="Top" OffContent="Repeat Off" OnContent="Repeat On"/>
                <TextBlock x:Name="tglBttnVolume" Margin="1155,681,0,0" HorizontalAlignment="Left" VerticalAlignment="Top" FontFamily="Webdings" FontSize="34" Text="U" Height="39"/>
                <Slider x:Name="sldrVolume" HorizontalAlignment="Left" Margin="1203,678,0,0" VerticalAlignment="Top" Width="135" Height="44" LargeChange="10" Maximum="100" StepFrequency="1" SmallChange="5" Background="#FF4486E6">
                </Slider>
                <Slider x:Name="prgsBarSongPosition" HorizontalAlignment="Left" Height="51" Margin="391,599,0,0" VerticalAlignment="Top" Width="948" Background="#FF4486E6" IsThumbToolTipEnabled="False"/>
            </Grid>
        </Viewbox>
    </Grid>
</Page>

MusicPlayer.xaml.cs file

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace MusicPlayer
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {
TextBlock txtPlayStatus = new TextBlock();
        public MainPage()
        {
            this.InitializeComponent();
            txtPlayStatus.Name = "txtPlayStatus";
            txtPlayStatus.Margin = new Thickness(390, 535, 25, 198);
            txtPlayStatus.FontSize = 18;
            txtPlayStatus.TextAlignment = TextAlignment.Center;
            grdMusicPlayer.Children.Add(txtPlayStatus);
        }
        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }
    }
}


Github Wolfman616 Xaml Ui Mod Modified System Ui Brushes For Windows

Github Wolfman616 Xaml Ui Mod Modified System Ui Brushes For Windows The control class is the base class for many of the controls you add to an app and its ui. the control class defines very little behavior; you can add an actual control element to xaml for ui but you typically add something that inherits from control directly or indirectly, such as a button or listbox. Equivalent winui 2 api for uwp: microsoft.ui.xaml.controls.bitmapiconsource (for winui in the windows app sdk, see the windows app sdk namespaces). border draws a border, background, or both, around another object.

Change App Configuration To Use The Win Ui Library Issue 1267

Change App Configuration To Use The Win Ui Library Issue 1267 Microsoft.ui.xaml.controls is the namespace used in the winui library. windows.ui.xaml.controls is the namespace of the native controls that are included in windows. Winui controls samples: each control page shows the markup and codebehind used to create each example. use the microsoft.ui.xaml (winui) library: the app includes the latest winui nuget package and shows how to use the winui controls like navigationview, swipecontrol, and more. The windows ui library (winui) provides official native microsoft ui controls and features for windows uwp apps. winui is the easiest way to build great fluent design experiences for windows. winui can be used in any windows 10 uwp xaml app, or in a xamarin.forms app running on windows 10 using native view embedding. An application with no greater ambition than helping you design or build a xaml universal windows application. showing you the list of controls from the sdk and a detailed view of each element. i hope it helps you know all the xaml properties related to visual states and to preview them.

Can I Use Custom Winui 3 Controls In Wpf Application Microsoft

Can I Use Custom Winui 3 Controls In Wpf Application Microsoft

Can I Use Custom Winui 3 Controls In Wpf Application Microsoft The windows ui library (winui) provides official native microsoft ui controls and features for windows uwp apps. winui is the easiest way to build great fluent design experiences for windows. winui can be used in any windows 10 uwp xaml app, or in a xamarin.forms app running on windows 10 using native view embedding. An application with no greater ambition than helping you design or build a xaml universal windows application. showing you the list of controls from the sdk and a detailed view of each element. i hope it helps you know all the xaml properties related to visual states and to preview them. Represents the base class for ui elements that use a controltemplate to define their appearance. parent class for contentcontrol, usercontrol, itemscontrol and several practical controls. more… the control class is the base class for many of the controls you add to an app and its ui. Represents a control that displays lightweight ui that is either information, or requires user interaction. unlike a dialog, a flyout can be light dismissed by clicking or tapping outside of it, pressing the device’s back button, or pressing the ‘esc’ key. This package provides backward compatible versions of windows ui features including uwp xaml controls, dense control styles, and fluent styles and materials. it is part of the windows ui library. versions compatible and additional computed target framework versions.

Microsoft Ui Xaml Controls Teachingtip Don T Work From Unpackaged Apps

Microsoft Ui Xaml Controls Teachingtip Don T Work From Unpackaged Apps Represents the base class for ui elements that use a controltemplate to define their appearance. parent class for contentcontrol, usercontrol, itemscontrol and several practical controls. more… the control class is the base class for many of the controls you add to an app and its ui. Represents a control that displays lightweight ui that is either information, or requires user interaction. unlike a dialog, a flyout can be light dismissed by clicking or tapping outside of it, pressing the device’s back button, or pressing the ‘esc’ key. This package provides backward compatible versions of windows ui features including uwp xaml controls, dense control styles, and fluent styles and materials. it is part of the windows ui library. versions compatible and additional computed target framework versions.

Hesam Seyed Mousavi, September 26, 2020

Begin by creating a new project in Microsoft Visual Studio. Create a Blank App (WinUI in UWP) project, set its name to BgLabelControlApp. Set the Target version to Windows 10, version 1903 (build 18362) and Minimum version to Windows 10, version 1803 (build 17134). This walkthrough will also work for desktop apps created with the Blank App, Packaged (WinUI in Desktop) project template, just make sure to perform all of the steps in the BgLabelControlApp (Desktop) project.

Source: erproject

blog.mousavi.fr

Blank App Project Template

Because the class will be instantiated from XAML markup, and for that reason it’s going to be a runtime class. The first step in authoring a new runtime class is to add a new Midl File (.idl) item to the project. From the Project menu, select Add New Item… and type “MIDL” in the search box to find the .idl file item. Name the new file BgLabelControl.idl so that the name will be consistent with the steps in this article. Delete the default contents of BgLabelControl.idl, and paste in this runtime class declaration. C++/WinRT

// BgLabelControl.idl
namespace BgLabelControlApp
{
    runtimeclass BgLabelControl : Microsoft.UI.Xaml.Controls.Control
    {
        BgLabelControl();
        static Microsoft.UI.Xaml.DependencyProperty LabelProperty{ get; };
        String Label;
    }
}

The listing above shows the pattern that you follow when declaring a dependency property (DP). There are two pieces to each DP. First, you declare a read-only static property of type DependencyProperty. It has the name of your DP plus Property. You’ll use this static property in your implementation. Second, you declare a read-write instance property with the type and name of your DP. If you wish to author an attached property (rather than a DP), then see the code examples in Custom attached properties.

Note that the XAML classes referenced in the code above are in Microsoft.UI.Xaml namespaces. This is what distinguishes them as WinUI controls as opposed to UWP XAML controls, which are defined in Windows.UI.XAML namespaces.

After saving the new .idl file, the next step is to generate the Windows Runtime metadata file (.winmd) and stubs for the .cpp and .h implementation files that you will use to implement the templated control. Generate these files by building the solution, which will cause the MIDL compiler (midl.exe) to compile the .idl file you created. Note that the Solution will not build successfully and Visual Studio will show build errors in the output window, but the necessary files will be generated.

Copy the stub files BgLabelControl.h and BgLabelControl.cpp from \BgLabelControlApp\BgLabelControlApp\Generated Files\sources\ into the project folder. In Solution Explorer, make sure Show All Files is toggled on. Right-click the stub files that you copied, and click Include In Project.

The compiler places a static_assert line at the top of BgLabelControl.h and BgLabelControl.cpp to prevent the generated files from being compiled. When implementing your control, you should remove these lines from the files you have placed in your project directory. For this walkthrough, you can just overwrite the entire contents of the files with the code provided below.

Implement the BgLabelControl custom control class

In the following steps you will update the code in the BgLabelControl.h and BgLabelControl.cpp files in the project directory to implement the runtime class.

Replace the contents of BgLabelControl.h with the following code. C++/WinRT

// BgLabelControl.h
#pragma once
#include "BgLabelControl.g.h"

namespace winrt::BgLabelControlApp::implementation
{
    struct BgLabelControl : BgLabelControlT<BgLabelControl>
    {
        BgLabelControl() { DefaultStyleKey(winrt::box_value(L"BgLabelControlApp.BgLabelControl")); }

        winrt::hstring Label()
        {
            return winrt::unbox_value<winrt::hstring>(GetValue(m_labelProperty));
        }

        void Label(winrt::hstring const& value)
        {
            SetValue(m_labelProperty, winrt::box_value(value));
        }

        static Microsoft::UI::Xaml::DependencyProperty LabelProperty() { return m_labelProperty; }

        static void OnLabelChanged(Microsoft::UI::Xaml::DependencyObject const&, Microsoft::UI::Xaml::DependencyPropertyChangedEventArgs const&);

    private:
        static Microsoft::UI::Xaml::DependencyProperty m_labelProperty;
    };
}
namespace winrt::BgLabelControlApp::factory_implementation
{
    struct BgLabelControl : BgLabelControlT<BgLabelControl, implementation::BgLabelControl>
    {
    };
}

The code shown above implements the Label and LabelProperty properties, add a static event handler named OnLabelChanged to process changes to the value of the dependency property, and adds a private member to store the backing field for LabelProperty.

Again, note that the XAML classes referenced in the header file are in the Microsoft.UI.Xaml namespaces that belong to the WinUI 3 framework instead of the Windows.UI.Xaml namespaces used by the UWP UI framework.

Next, replace the contents of BgLabelControl.cpp with the following code. C++/WinRT

// BgLabelControl.cpp
#include "pch.h"
#include "BgLabelControl.h"
#include "BgLabelControl.g.cpp"

namespace winrt::BgLabelControlApp::implementation
{
    Microsoft::UI::Xaml::DependencyProperty BgLabelControl::m_labelProperty =
        Microsoft::UI::Xaml::DependencyProperty::Register(
            L"Label",
            winrt::xaml_typename<winrt::hstring>(),
            winrt::xaml_typename<BgLabelControlApp::BgLabelControl>(),
            Microsoft::UI::Xaml::PropertyMetadata{ winrt::box_value(L"default label"), Microsoft::UI::Xaml::PropertyChangedCallback{ &BgLabelControl::OnLabelChanged } }
    );

    void BgLabelControl::OnLabelChanged(Microsoft::UI::Xaml::DependencyObject const& d, Microsoft::UI::Xaml::DependencyPropertyChangedEventArgs const& /* e */)
    {
        if (BgLabelControlApp::BgLabelControl theControl{ d.try_as<BgLabelControlApp::BgLabelControl>() })
        {
            // Call members of the projected type via theControl.

            BgLabelControlApp::implementation::BgLabelControl* ptr{ winrt::get_self<BgLabelControlApp::implementation::BgLabelControl>(theControl) };
            // Call members of the implementation type via ptr.
        }
    }
}

This walkthrough won’t use the OnLabelChanged callback, but it’s provided so that you can see how to register a dependency property with a property-changed callback. The implementation of OnLabelChanged also shows how to obtain a derived projected type from a base projected type (the base projected type is DependencyObject, in this case). And it shows how to then obtain a pointer to the type that implements the projected type. That second operation will naturally only be possible in the project that implements the projected type (that is, the project that implements the runtime class).

The xaml_typename function is provided by the Windows.UI.Xaml.Interop namespace that is not included by default in the WinUI 3 project template. Add a line to the precompiled header file for your project, pch.h, to include the header file associated with this namespace. C++/WinRT

// pch.h
...
#include <winrt/Windows.UI.Xaml.Interop.h>
...

Design the default style for BgLabelControl

In its constructor, BgLabelControl sets a default style key for itself. A templated control needs to have a default style — containing a default control template — which it can use to render itself with in case the consumer of the control doesn’t set a style and/or template. In this section we’ll add a markup file to the project containing our default style.

Make sure that Show All Files is still toggled on (in Solution Explorer). Under your project node, create a new folder (not a filter, but a folder) and name it “Themes”. Under Themes, add a new item of type Visual C++ > XAML > XAML View, and name it “Generic.xaml”. The folder and file names have to be like this in order for the XAML framework to find the default style for a templated control. Delete the default contents of Generic.xaml, and paste in the markup below. XAML

<!-- \Themes\Generic.xaml -->
<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:BgLabelControlApp">

    <Style TargetType="local:BgLabelControl" >
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="local:BgLabelControl">
                    <Grid Width="100" Height="100" Background="{TemplateBinding Background}">
                        <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="{TemplateBinding Label}"/>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

In this case, the only property that the default style sets is the control template. The template consists of a square (whose background is bound to the Background property that all instances of the XAML Control type have), and a text element (whose text is bound to the BgLabelControl::Label dependency property).

Add an instance of BgLabelControl to the main UI page

Open MainPage.xaml, which contains the XAML markup for our main UI page. Immediately after the Button element (inside the StackPanel), add the following markup. XAML

<local:BgLabelControl Background="Red" Label="Hello, World!"/>

Also, add the following include directive to MainPage.h so that the MainPage type (a combination of compiling XAML markup and imperative code) is aware of the BgLabelControl templated control type. If you want to use BgLabelControl from another XAML page, then add this same include directive to the header file for that page, too. Or, alternatively, just put a single include directive in your precompiled header file. C++/WinRT

//MainPage.h
...
#include "BgLabelControl.h"
...

Now build and run the project. You’ll see that the default control template is binding to the background brush, and to the label, of the BgLabelControl instance in the markup.

Implementing overridable functions, such as MeasureOverride and OnApplyTemplate

You derive a templated control from the Control runtime class, which itself further derives from base runtime classes. And there are overridable methods of Control, FrameworkElement, and UIElement that you can override in your derived class. Here’s a code example showing you how to do that. C++/WinRT

// Control overrides.
void OnPointerPressed(Microsoft::UI::Xaml::Input::PointerRoutedEventArgs const& /* e */) const { ... };

// FrameworkElement overrides.
Windows::Foundation::Size MeasureOverride(Windows::Foundation::Size const& /* availableSize */) const { ... };
void OnApplyTemplate() const { ... };

// UIElement overrides.
Microsoft::UI::Xaml::Automation::Peers::AutomationPeer OnCreateAutomationPeer() const { ... };

Overridable functions present themselves differently in different language projections. In C#, for example, overridable functions typically appear as protected virtual functions. In C++/WinRT, they’re neither virtual nor protected, but you can still override them and provide your own implementation, as shown above.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как зайти в аккаунт администратора windows 10
  • Everything download windows 10
  • Гаджет пак для windows 10
  • Где хранится дамп синего экрана в windows 10
  • Microsoft other hardware xbox wireless adapter for windows