Universal Windows Platform Tips for Microsoft Visual Studio and .NET developers. Take your Windows App skills up a notch.
Sunday, January 19, 2020
Mastering Xamarin.Forms Book Review on Morning Dew
Go check out my full review of the book on my Morning Dew blog.
Happy Coding!
Sunday, September 15, 2019
Quick Tip - Hot Fix Update for Windows Template Studio Now Available
Last week, Windows Template Studio version 3.4.19254.01 was released to address two issues specific to the VS2019 Preview.
- Issue #3295 - Relates to adding an MVVM Light app to a Windows Template Studio project.
- Issue #3309 - An error occurs when generating a project with the default selections.
There are no workarounds listed for either issue. Although both are specific to VS2019 Preview and seem to be limited in the scope of their problems, I like to patch my dev software as fixes become available. You can install this update whether you're running WTS with VS2017 or VS2019 Release/Preview.
You can either get the VSIX for the release here or if you have Windows Template Studio installed, open the Visual Studio Extensions dialog and check for updates. The source code for the release is also available for download if you want to have a peek under the hood.
Happy coding!
Sunday, February 10, 2019
UWP Tip #25 - Windows Community Toolkit - Using the TabView Control
Let's start by viewing the control in the handy toolkit sample app that you can install from the Microsoft Store. I added a yellow border to identify the bounds of the control itself.
You can see that the control has header and footer regions, a row of tabs with the ability to add tabs using the + icon, and a settings button to enable user configuration of the tab behavior. Based on the settings exposed on the right through the sample app, you can also see that it is easy to change the tab width settings, add close tab buttons and provide drag-and-drop behavior to rearrange tabs.
Let's crate a new UWP project and get our hands on some XAML. Once your project is created, add the Microsoft.Toolkit.Uwp.UI.Controls v5.0 (or later) NuGet package. I have also added MVVMLight for some quick MVVM support.
Let's keep the XAML really simple for our first test run with the TabView. Here is the markup for a TabView with a header, footer and four tabs.
<Grid> <controls:TabView> <controls:TabView.Header> <TextBlock Text="Top of the World!"/> </controls:TabView.Header> <controls:TabViewItem Header="First Tab"> <TextBlock Text="First tab Contents!"/> </controls:TabViewItem> <controls:TabViewItem Header="Tab 2"> <TextBlock Text="Tab 2 contents!"/> </controls:TabViewItem> <controls:TabViewItem Header="3rd Tab"> <TextBlock Text="3rd tab contents!"/> </controls:TabViewItem> <controls:TabViewItem Header="Last Tab"> <TextBlock Text="Last tab contents!"/> </controls:TabViewItem> <controls:TabView.Footer> <TextBlock Text="The End"/> </controls:TabView.Footer> </controls:TabView> </Grid>
If you want to see an example with a little more complexity, check out the XAML tab for the TabView in the toolkit sample app. Here is what our XAML renders at runtime.
It doesn't look to bad for a view lines of XAML, if you ask me. We are all ready to plug in four tabs full of great content, and we support Windows theming out of the box. Hover over the tabs and see how they have a nice, fluent look and feel also. Very cool!
Before we wrap up this simple example, let's clean things up with some margins on our TextBlock elements and copy some XAML from the sample app to get that cool Settings icon at the end of our tab row. Here is that markup:
<controls:TabView.TabEndHeader>
<Button Width="48"
Height="40"
Margin="-1,0,0,0"
BorderThickness="1"
Background="Transparent"
Style="{StaticResource ButtonRevealStyle}">
<Viewbox MaxWidth="16" MaxHeight="16">
<SymbolIcon Symbol="Setting"/>
</Viewbox>
</Button>
</controls:TabView.TabEndHeader>
Place this between your last TabViewItem and the TabView.Footer element. This is the what our Page looks like now.
Now our text has a little breathing room, and our tabs have a settings button. (It's up to you to add the settings, of course.)
That's it for our quick tour of the TabView. There's loads more to explore in this control. I recommend starting with the MS Docs page for the control, and then head over to the GitHub repo to check out the source.
Happy coding!
Saturday, January 19, 2019
UWP Tip #24 - Get Started Building Windows UI XAML with XAML Studio
What Is XAML Studio
XAML Studio aims to provide Windows UI developers with a quick way to create and prototype XAML markup for Windows. If you miss old lightweight XAML editors like XamlPad, you should install XAML Studio today. These are a few of the features already available in this early version of the tool.- Live Preview
- Live Binding
- Binding Debugging
- Data Context Editor
- Auto-Save (with Restore)
- IntelliSense
- Documentation Toolbox with Links to MS Docs
- Alignment Guides
- Namespace Helpers
Getting Started
You can search for XAML Studio in the Microsoft Store and install it from there or use this handy link. When you open the app for the first time, you'll be greeted by a Welcome screen like this.XAML Editor
If you have an existing WinUI XAML file you would like to try, you can use the Open File link. Let's get started today by clicking the New File link to create and start editing your first XAML file.The new XAML file is a Windows Page containing a Grid with a 2-line TextBlock. Let's start slow and the Run text of each line a little bit to read "Get Started with XAML Studio on UWP Tips" and "Check out the live preview.". You'll notice that the live preview is exactly that... live. The text in the preview will refresh as you change it in the editor.
IntelliSense and Live Preview
Let's test out the IntelliSense by adding a couple more controls to the page. We'll switch out the Grid for a StackPanel with the default vertical orientation and add a Button and another TextBlock.Settings
The IntelliSense is quite nice, but I think the default Live Preview refresh interval is a little fast. The bright pink error messages about invalid markup are distracting while working in the editor. You can either disable auto-compilation or edit the interval in the app's settings. The default interval is to compile after 0.8 seconds of inactivity in the editor. I updated mine to 2 seconds.You should take some time to explore all of the XAML Studio settings as you're getting familiar with the app.
Documentation Toolbox
Something else you should explore is the Documentation Toolbox in the left panel.Here you can view all of the WinUI XAML controls available to the editor, complete with little info icons that link to the Microsoft Docs online documentation. The control name and namespace appear in the list for each item. If you have controls that you frequently use, you can add them to your favorites so they always appear at the top of the list.
Data Binding
Want to add some dynamic content to your page without coding up your model, view model or connecting to a live data source? You can create a mocked up data source with some JSON data in the Data Source pane on the left.For this prototype, I grabbed some sample JSON data from one of Adobe's sites. This data contains an array of donuts, each with its own array of batters and toppings and some other properties. It's a handy bit of small, yet semi-complex data.
From the Data Source pane, you can save your JSON, open other JSON data files, or connect to a Remote Data Context. Using a remote data context is as simple as entering a REST Url that returns valid JSON data. The returned data will populate your Data Source window and can be saved for later use.
Here is my XAML markup from the screenshot above with bindings added for the donut JSON data.
<StackPanel Padding="40" DataContext="{Binding}"> <TextBlock Margin="8"> <Run FontSize="24" Foreground="#FFFC5185">Get Started with XAML Studio on UWP Tips</Run><LineBreak/> <Run>Check out the live preview.</Run> </TextBlock> <Button Content="I Do Nothing" Margin="8"/> <ListView ItemsSource="{Binding}"> <ListView.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal"> <TextBlock Text="{Binding Path=id}" Margin="4"/> <TextBlock Text="{Binding Path=type}" Margin="4"/> <TextBlock Text="{Binding Path=name}" Margin="4"/> <TextBlock Text="{Binding Path=rating}" Margin="4"/> </StackPanel> </DataTemplate> </ListView.ItemTemplate> </ListView> </StackPanel>
These binding expressions are all valid except for one. Want to quickly know which of your bindings is invalid? Switch to the Debug Bindings pane and turn on the Debug toggle.
After debug is enabled on bindings, a list of the binding expressions will display in the pane with a 'Successful' or 'NotBound' status next to the binding target. A timestamp of the last bound time will display with any bindings that have been successful. In addition, the binding expressions in the code editor will be highlighted to indicate their status, making it easier to navigate to the failed bindings.
In my case, I tried to bind to a "rating" property, which does not exist on the donut array items in the JSON data.
Next Steps
That's all we're going to explore in this intro to XAML Studio. Next time we'll dive a little deeper into remote bindings, bind some more complex controls, and see how easily we can take our prototype XAML over to a real UWP application in Visual Studio.Go check out XAML Studio today and be sure to provide feedback to Michael on Twitter!
Happy XAMLing!
Friday, November 2, 2018
Windows Developer Resource Roundup - November 2018 Edition
I typically leave the link blogging over on the Morning Dew, but I thought my readers here might appreciate a post with a rundown of useful resources for Windows developers.
GitHub Repositories
We'll start off with some GitHub repos that I have starred. The organizations behind each repo are listed in parentheses.
Windows UI Library (Microsoft) - These are the Microsoft UWP XAML controls/styles/materials created for backward compatibility across Windows 10 versions back to the Anniversary Update. As new features are added, you can immediately make them available to your apps across all of these versions of Windows.
Windows Community Toolkit (Windows Community Toolkit) - If you follow my blog, you're very familiar with this toolkit. Formerly known as the UWP Community Toolkit, it now provides a phenomenal set of controls, helpers and services for all Windows developers.
Windows Template Studio (Microsoft) - I've also blogged about this extension on several occasions. WTS provides templates for Visual Studio and a wizard to bootstrap your UWP app with a great foundation built on popular tools and good patterns & practices.
Rapid XAML Toolkit (Microsoft) - This toolkit is a newer community effort spearheaded by Matt Lacey. It is still in preview and aims to accelerate app development for all XAML developers - UWP, WPF, and Xamarin.Forms. I blogged about the toolkit a couple of weeks ago if you would like to learn more.
Fluent XAML Theme Editor (Microsoft) - This is the source code for the Fluent XAML Theme Editor app, now available in the Windows Store. Build your own Fluent theme with light and dark support and use it in your own apps. The app requires Windows SDK version 17763 or higher.
Prism (Prism Library) - Prism is the ultimate framework for XAML developers, with support for WPF, UWP, and Xamarin.Forms. Make your apps more maintainable and testable with simple and robust MVVM, DI, commands and other patterns & tools.
MVVM Light Toolkit (Laurent Bugnion) - MVVM Light offers an alternative to the MVVM framework provided in Prism. It supports UWP, WPF and Xamarin Forms/iOS/Android. This was the first MVVM library I used and it's still a favorite when putting together sample apps.
Documentation
A good framework or toolkit needs great documentation, right? Get the docs here, or contribute to them with your own expertise!
Universal Windows Platform Docs - The Microsoft Docs landing page for all UWP documentation. There are resources to get started, design, develop and publish your apps, as well as a full API reference.
Windows Community Toolkit Docs - The Microsoft Docs home for Windows Community Toolkit docs. Get help with controls or helpers in the toolkit, use get a reference for APIs or contribute to the docs yourself.
Prism Documentation - The official docs for the Prism Library. There are some general guides and sections specific to WPF and Xamarin.Forms.
MVVM Light Documentation - The MVVM Light docs have some samples, walkthroughs, and a link to a fundamentals course on Pluralsight.
Blogs
Keep up with the latest news.
Windows Developer Blog - The official Microsoft blog for the Windows Dev team. Subscribe for updates on SDKs, toolkits, Windows 10 releases and more.
Windows 10 Blog - This blog is the place to get announcements of new Windows features, upcoming events, and releases of new Windows 10 builds (final and Insiders).
The Visual Studio Blog - If you're a Windows developer, there's a pretty good chance you use Visual Studio. Keep up with the latest VS news here.
XAML Brewer - Diederik Krols has some great UWP tutorials on his blog, most recently about improving accessibility in a control.
Official Microsoft Sites
Windows Dev Center - The Microsoft hub for Windows developers. This site has links to all the resources Windows developers need today. Get to docs, tools, SDKs, events, design resources, and register to sell your apps on the Store through the Partner Center dashboard.
Visual Studio App Center - Sign up for the App Center can get continuous integration against your app's repo, test it on actual devices with automation, and deploy to beta testers and production users. You can also get crash reports and analytics with a few API hooks in your app.
Microsoft Design - Get information about the Fluent Design System and start designing and developing your apps with Fluent Design.
Windows Community Toolkit Sample App - Get the sample app to demo the components inside the Windows Community Toolkit.
Visual Studio Marketplace - Windows Template Studio - Download and install WTS from the VS Marketplace. Love the tool? Leave a review!
Other Sites
Prism LIbrary - Prism's home page. It's got links to their docs, learning resources and their Slack channel.
MVVM Light Toolkit - The MVVM Light homepage.
Stack Overflow - Questions tagged "uwp" on Stack Overflow.
@windowsdev - Follow the Windows Developer team on Twitter.
#ifdef WINDOWS - Join Nikola Metulev, Sr. Program Manager for Windows Dev, for a regular video series on Channel 9 where he interviews engineers on the Windows platform.
That's all I have for this first edition. If you have suggestions for future posts, please leave a comment or ping me on Twitter. I plan on posting these semi-annually, but if I get enough suggestions, I may have to create a second edition sooner. Thanks!
Saturday, October 13, 2018
UWP Tips Early Look - Rapid XAML Toolkit (Beta)
Note: The Rapid XAML Toolkit isn't UWP-specific. You can leverage these tools for WPF and Xamarin.Forms development. XAML developers, check it out today!
In today's tip, we will have a peek at a cool project still in early beta stages, the Rapid XAML Toolkit. What is this toolkit? From their readme.md on GitHub:
These tools aim to reduce the time and effort required to get the basics working and allow you to customize the UI to meet your preferences or the specific needs of your app. We can't and don't try to create the whole app for you but we can make creating and working with XAML faster easier.In short, the toolkit can take a set of properties from a ViewModel in your project and generate XAML controls in your corresponding View.
To give this a try, you will need to download the source and run it in an experimental instance of Visual Studio. Get the full instructions from the getting started guide here. No VSIX file is available yet to run the toolkit in VS itself. That will be coming later. Let's give it a try.
You should have completed these steps from the getting started guide:
- Clone or download the Rapid XAML Toolkit solution
- Open and build the solution
- Run/Debug the toolkit solution in an experimental VS instance
You could also open an existing UWP project, if you have one handy. If not, add a new ViewModel, some model classes, and set up your data context, using your favorite MVVM toolkit/method. One other thing you will need to set up is in the Rapid XAML Toolkit settings in your VS options:
Select a Profile and click "Set as Active". This will control how your copied ViewModel data is prepared and converted to XAML for your view. Save your settings, return to one of your viewmodel classes and highlight some properties to be copied. Then right-click and select the Rapid XAML menu:
You can either copy the converted XAML to your clipboard or send it to your VS Toolbox to be dragged to your view(s). Next, open a view and paste those properties into the XAML editor.
For this given ViewModel data that was copied:
public string PatientName { get; private set; }
public int SSN { get; set; }
public DateTimeOffset VisitDate { get; set; }
public string VisitNotes { get; set; }
public decimal CurrentWeight { get; }
public ObservableCollection<Medication> Prescriptions { get; set; }
For reference, this is the Medication model class:
public class Medication
{
public int Id { get; set; }
public string Name { get; set; }
public string UnitOfMeasure { get; set; }
public double Strength { get; set; }
}
You will have this XAML markup pasted:<TextBlock Text="{Binding PatientName}" />
<Slider Minimum="0" Maximum="100" x:Name="SSN" Value="{Binding SSN, Mode=TwoWay}" />
<DatePicker Date="{Binding VisitDate, Mode=TwoWay}" />
<TextBox Text="{Binding VisitNotes, Mode=TwoWay}" />
<TextBlock Text="{Binding CurrentWeight}" />
<ListView ItemsSource="{Binding Prescriptions}">
<ListView.ItemTemplate>
<DataTemplate x:DataType="model:Medication">
<StackPanel>
<TextBlock Text="{x:Bind Id, Mode=OneWay}" />
<TextBlock Text="{x:Bind Name, Mode=OneWay}" />
<TextBlock Text="{x:Bind UnitOfMeasure, Mode=OneWay}" />
<TextBlock Text="{x:Bind Strength, Mode=OneWay}" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
I'll grant that it doesn't create the prettiest UI, but it is still an early beta and very little editing is required from this point to create something usable. Here is what the generated view looks like to a user:Keep an eye on this project. I have a feeling it is going to eventually be a big time-saver for Windows devs. If you are the adventurous type, go out and download the beta source today. Have an idea to improve the toolkit? Create an issue on GitHub and start a discussion.
Happy coding!
Sunday, September 9, 2018
UWP Tip #23 - Windows Community Toolkit - Microsoft Translator and Bing Services
Welcome back to another UWP Tip focusing on the Windows Community Toolkit.
Services Intro
The Windows Community Toolkit contains a growing collection of services that provide easy access to services from Microsoft and other sources. These are the services available to developers in version 4.0 of the toolkit.
- Facebook - Login, get data from a user's feed, photos, and more.
- LinkedIn - Login, get user profile information, share a post to a user's feed.
- Twitter - Receive tweets, search Twitter, post a new tweet, and more.
- Bing - Search Bing
- OneDrive - Login and get file and folder info, manipulate files and more.
- Microsoft Translator - Translate text between languages supported by the service.
- Microsoft Graph Service - Login, send messages, get user info from Azure AD, get user events and more.
This post will illustrate how to use the Bing and Microsoft Translator services with some simple examples. The examples wrap the two services in our own application service class which could be used by a UWP app or other Windows application.
Microsoft Translator Service
To use the Translator service, an application key for the service is necessary. Developers can register for a key here.
The TranslateTextAsync async method will take three parameters:
- sourceLanguage
- destinationLanguage
- sourceText
The source and destination languages are passed to the translate method in the form of 'friendly names' of each language. To the the entire list of these names, use the service method TranslatorService.Instance.GetLanguageNamesAsync(). Another option is to attempt detection of the source language with the method TranslatorService.Instance.DetectLanguageAsync(string).
Here is the complete code for our method.
private const string MyTranslatorKey = "<your key here>";
public async Task<string> TranslateTextAsync(string sourceLanguage, string destinationLanguage, string sourceText) {
await TranslatorService.Instance.InitializeAsync(MyTranslatorKey);
// Translates the source text to from the specified source language to the destination language.
return await TranslatorService.Instance.TranslateAsync(sourceText, sourceLanguage, destinationLanguage); }
Bing Service
NOTE: The Bing service has been marked as obsolete as of Windows Community Toolkit 4.0. The team recommends using the Cognitive Services SDK moving forward. That SDK can be found here on GitHub.
The Bing API requires an API key, which can be obtained here. There is a free trial account available. Sign up, select the free options, and get access to up to 5000 queries per month from your applications. Our SearchAsync(string, int) method will create a searchConfig object which will tell the service to search from the U.S. using English language and perform a standard search. A News search type is also available. The method will then perform the search and return the number of BingResult record types specified by the numberofResults parameter.
public async Task<List<BingResult>> SearchAsync(string searchText, int numberOfResults)
{
if (string.IsNullOrWhiteSpace(searchText))
{
return null;
}
var searchConfig = new BingSearchConfig
{
Country = BingCountry.UnitedStates,
Language = BingLanguage.English,
Query = searchText,
QueryType = BingQueryType.Search
};
return await BingService.Instance.RequestAsync(searchConfig, numberOfResults);
}
Easy-peasy, right? After the next major release of the Windows Community Toolkit, we will examine how to perform the same types of queries with the Cognitive Services SDK.
Wrap-Up
These are a couple of easy-to-consume services that developers can use today in their applications by simply adding the required Windows Community Toolkit NuGet packages. To check out the complete docs for the available services, visit Microsoft Docs.
Happy coding!
Thursday, August 9, 2018
UWP Tip #22 - Windows Community Toolkit 4.0 Released - DataGrid Is Ready For Your Production Apps
New Release
It's another milestone for the Windows Community Toolkit. Yesterday on the Windows Developer blog, Nikola Metulev announced that the Windows Community Toolkit v4.0 had been released. These are the major changes, according to the release notes on GitHub:- DataGrid control is now released out of preview
- 2 Microsoft Graph controls were added:
- WebView control enhancements
- Services (Twitter, LinkedIn, MS Translator) moved Microsoft.Toolkit.Services. Anyone targeting .NET Standard 1.4 can now use these.
- Twitter service enhanced to include some missing properties from Twitter tweet API
- Windows Community Toolkit Sample App updated to implement fluent design and a dark theme!
- Assembly strong naming
- Dozens of bug fixes in controls, helpers, services and documentation
DataGrid Control
The DataGrid XAML control feel be immediately familiar to any developers who have used the Silverlight DataGrid. This control shares the functionality of the old Silverlight control. In fact, the docs for the DataGrid actually link to the Silverlight DataGrid's API for reference.As usual, Microsoft's docs are a great place to start. There are eight How-To's for the DataGrid available, so I won't provide my own simple walkthrough here. Instead, let's explore DataGrid in the newly updated Windows Community Toolkit Sample App.
Open the sample app, and select the DataGrid from the Controls menu.
As you can see, I'm already taking advantage of the addition of the dark theme support in the latest release of sample app.
You'll be presented with a DataGrid control filled with data about mountains. Let's take a minute to thank the developers who worked on the sample app for not providing users with yet another invoicing or inventory set of data.
Speaking of Themes, did you notice another new feature of the sample app? You can select System, Light or Dark to apply themes to the individual controls displayed within the sample app. How useful!
Just below this, in the header area just above the DataGrid itself, users are able to Filter or Group the grid data with a set of AppBarButton controls. This is the default code for the header:
<StackPanel Orientation="Horizontal" Margin="12">
<TextBlock Text="DataGrid Sample : Mountains" VerticalAlignment="Center" Margin="5,0" Style="{ThemeResource SubtitleTextBlockStyle}"></TextBlock>
<AppBarButton Icon="Filter" Label="Filter by">
<AppBarButton.Flyout>
<MenuFlyout>
<MenuFlyoutItem x:Name="rankLow" Text="Rank < 50" />
<MenuFlyoutItem x:Name="rankHigh" Text="Rank > 50" />
<MenuFlyoutSeparator />
<MenuFlyoutItem x:Name="heightLow" Text="Height < 8000ft" />
<MenuFlyoutItem x:Name="heightHigh" Text="Height > 8000ft" />
</MenuFlyout>
</AppBarButton.Flyout>
</AppBarButton>
<AppBarButton x:Name="groupButton" Icon="List" Label="Group by" />
</StackPanel>
The code for the DataGrid primarily consists of a number or properties and then a DataGridTextColumn for each column added to the control. Here's that code:<controls:DataGrid
Grid.Row="1"
x:Name="dataGrid"
Margin="12"
VerticalAlignment="Stretch" HorizontalAlignment="Stretch"
HorizontalScrollBarVisibility="Visible"
VerticalScrollBarVisibility="Visible"
AlternatingRowBackground="Transparent"
AlternatingRowForeground="Gray"
AreRowDetailsFrozen="False"
AreRowGroupHeadersFrozen="True"
AutoGenerateColumns="False"
CanUserSortColumns="False"
CanUserReorderColumns="True"
CanUserResizeColumns="True"
ColumnHeaderHeight="32"
MaxColumnWidth="400"
FrozenColumnCount="0"
GridLinesVisibility="None"
HeadersVisibility="Column"
IsReadOnly="False"
RowDetailsTemplate="{StaticResource RowDetailsTemplate}"
RowDetailsVisibilityMode="Collapsed"
SelectionMode="Extended"
RowGroupHeaderPropertyNameAlternative="Range">
<controls:DataGrid.Columns>
<controls:DataGridTextColumn Header="Rank" Binding="{Binding Rank}" Tag="Rank" />
<controls:DataGridTextColumn Header="Mountain" Binding="{Binding Mountain}" Tag="Mountain" />
<controls:DataGridTextColumn Header="Height (m)" Binding="{Binding Height_m}" Tag="Height_m" />
<controls:DataGridTextColumn Header="Range" Binding="{Binding Range}" Tag="Range" />
<controls:DataGridTextColumn Header="Parent Mountain" Binding="{Binding Parent_mountain}" Tag="Parent_mountain" />
</controls:DataGrid.Columns>
</controls:DataGrid>
For the purposes of a sample app, everything but the grid data is hard coded. Your app could certainly bind any of these properties that you would like to either load from saved configuration or user preferences.Let's round out our look at the sample app's code by reviewing the DataTemplate for the row details.
<DataTemplate x:Key="RowDetailsTemplate">
<StackPanel>
<TextBlock Margin="20" Text="Here are the details for the selected mountain:" />
<Grid Margin="20,10" Padding="5">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Text="Coordinates: " FontWeight="SemiBold" FontSize="13" />
<TextBlock Grid.Row="1" Text="Prominence (m): " FontWeight="SemiBold" FontSize="13" />
<TextBlock Grid.Row="2" Text="First Ascent (year): " FontWeight="SemiBold" FontSize="13" />
<TextBlock Grid.Row="3" Text="No. of ascents: " FontWeight="SemiBold" FontSize="13" />
<TextBlock Grid.Column="1" FontSize="13" Text="{Binding Coordinates}" HorizontalAlignment="Right" />
<TextBlock Grid.Row="1" Grid.Column="1" FontSize="13" Text="{Binding Prominence}" HorizontalAlignment="Right" />
<TextBlock Grid.Row="2" Grid.Column="1" FontSize="13" Text="{Binding First_ascent}" HorizontalAlignment="Right" />
<TextBlock Grid.Row="3" Grid.Column="1" FontSize="13" Text="{Binding Ascents}" HorizontalAlignment="Right" />
</Grid>
</StackPanel>
</DataTemplate>
If a user were to view details on a row, this is how the information would be displayed. The sample app does not appear to currently implement a way to display the RowDetailsTemplate in the UI.Wrap-Up
Go explore the source code, read the docs and play with the sample app. Then add the DataGrid to your own Windows app! It's a powerful grid control that will save you loads of time.Happy coding!
Friday, July 27, 2018
UWP App Tips Announcement - Windows UI LIbrary (WinUI)
Big news for Windows developers this week!
On Monday, the Windows Developer team announced the preview release of the Windows UI Library. Windows UI Library, or WinUI, is a set of NuGet packages which contain UWP XAML controls and other features which can be used across different versions of Windows 10. Many of these will be compatible with release from 1607 to the latest Insiders Fast Ring builds.
Windows developers will no longer need to wait for their users to adopt the latest Windows 10 release in order to provide some of the rich features provided by these packages, like Fluent controls.
WinUI preview currently consists of two NuGet packages:
- Microsoft.UI.Xaml - Contains new and updated XAML controls for UWP applications.
- Microsoft.UI.Xaml.Core.Direct - Provides access to XamlDirect APIs on versions of Windows 10 that do not yet support these APIs.
Want to get started with WinUI? Here's a quick step-by-step guide to creating a project, adding the NuGet packages, and adding a couple of the new XAML controls to your main Window. Want to add WinUI to an existing UWP project? As long as your project's Minimum version is at least 14393 and Target version is 17134 or later, you can follow the same steps to add the NuGet packages.
First, create your project in Visual Studio 2017 (VS 2015 is not supported).
Next, open the NuGet package management window for your project. Select Browse, and search for Microsoft.UI.Xaml. Be sure to select the "Include prerelease" checkbox next to the search field or you will see no results.
Add the packages you want to use. After adding Microsoft.UI.Xaml, a readme file will open advising you to add the following snippet to your project's App.xaml. Be sure you do this immediately after installing the package.
<Application.Resources>
<XamlControlsResources xmlns="using:Microsoft.UI.Xaml.Controls"/>
</Application.Resources>
Now you can close your NuGet Package Manager and the readme.txt and App.xaml files. Let's add a couple of new and updated controls to MainPage.xaml. Start by adding a reference to your Page:
xmlns:winUiControls="using:Microsoft.UI.Xaml.Controls"
I've added a few controls to my Page, a TwoPaneView containing a SplitButton in Pane1 and a PersonPicture in Pane2.
<winUiControls:TwoPaneView>
<winUiControls:TwoPaneView.Pane1>
<Grid>
<winUiControls:SplitButton Content="Click or Select" Margin="12"/>
</Grid>
</winUiControls:TwoPaneView.Pane1>
<winUiControls:TwoPaneView.Pane2>
<Grid>
<winUiControls:PersonPicture/>
</Grid>
</winUiControls:TwoPaneView.Pane2>
</winUiControls:TwoPaneView>
The result is exactly what you would expect for this snippet.
So, what controls are included in the Microsoft.UI.Xaml package? If you open Object Browser, you will currently find a huge list classes under the Microsoft.UI.Xaml.Controls namespace. A few of the new and updated controls include:
- ColorPicker
- DropDownButton
- SplitButton
- LayoutPanel
- MenuBar
- NavigationView
- ParallaxView
- RatingControl
- PersonPicture
- Repeater
- Scroller
- SwipeItem
- TreeView
- TwoPaneView
Lots to love for sure. Documentation of the classes in this namespace can be found here, although much of it is currently limited and only labeled as prerelease.
Ready to play? Go check out the Getting Started article on MS Docs and the XAML Controls Gallery code on GitHub! Remember this is currently prerelease code and may undergo some change before it goes RTM.
Happy coding!
Wednesday, June 27, 2018
UWP Tip #21 - File-->New Project with Windows Template Studio 2.2
Windows Template Studio 2.2 was released about two weeks ago. You can view the full list of new features, enhancements and bug fixes on the GitHub repo here. These are a few of the highlights.
- Support adding a 3D app launcher for when the app is used in MR
- Documentation improvements (multiple issues)
- Unit Testing improvements (multiple issues)
- Platform uplift (UWP, Telerik, Windows Community Toolkit, and more)
You can install the latest version of Windows Template Studio from the Visual Studio Marketplace or in Visual Studio's extension manager.
Let's walk through the new project creation process with Windows Template Studio in Visual Studio 2017. Start with File-->New Project.
Select the Windows Template Studio (Universal Windows) project type, give your project a name and click OK. Next you'll start with the project wizard.
Start the wizard by choosing your project type.
- Navigation Pane
- Blank
- Pivot and Tabs
I'm going to select the Navigation Pane type, which gives you a familiar left navigation area with a hamburger menu. Select Next to move on to Design Pattern.
Choose your project's design pattern/package.
- Code Behind
- MVVM Light
- MVVM Basic
- Caliburn.Micro
- Prism
I usually choose MVVM Light for my sample applications and other simple projects. Today I am going to select Prism to see what is generated by Windows Template Studio for this pattern.
Click Next to move on to selecting what types of pages to include in your application.
There are eleven types of pages from which to choose. Select the ones to be included in your project.
- Blank
- Settings
- Web View
- Media Player
- Master/Detail
- Telerik Data Grid
- Chart
- Tabbed
- Map
- Camera
- Image Gallery
In addition to the default Main page selected, I've chosen to add a Web View named DewWebViewPage, a Settings page, and a Telerik Grid Page named SharedItemsGridPage.
Click Next again and we'll finish up by selecting some optional features to add to the app.
Version 2.2 now has 17 features to select for your app. Pick the ones that best suit your application's needs and feature set and click Finish to generate your project.
Now that the project has been created, you should see the default UWP welcome screen with some helpful links and your Solution Explorer. I'm going to start by taking a look at what NuGet packages were added for my project.
Based on my wizard selections, I have a handful of packages referenced by my project, including those for Prism.Unity and Telerik.UI.UWP. Your result will vary based on the pattern, pages and features selected for your project.
Next, let's expand a few of the project folders to examine the files created for the project.
You should see a View and corresponding ViewModel for each of the Pages you selected for your app, assuming you did not select the Code Behind pattern. In that case, there will be no ViewModel classes.
The Services and Helpers will also vary from those above based on your feature selections.
In my case, there is a SampleOrder in the Models folder for use with the Data Grid. This will be changed to mirror the actual model to be used in the application's grid. The SampleDataService and its corresponding interface will be used to populate the grid. The WebView also has a service and a service interface for testability.
Run the app and try it out. All of the base navigation functionality is there and works great.
The Main Page
The WebView
The Data Grid
The Settings… let's change to the Dark Theme while we're in here.
That's it for the basics. Stay tuned for the next part where we will examine some of the code files and make some tweaks to make it fit your application's requirements.
Happy coding!
Monday, June 4, 2018
UWP Tip #20 - Windows Community Toolkit - Part 16, InfiniteCanvas
Welcome back to my Windows Community Toolkit series, formerly known as the UWP Community Toolkit series (see this post). The previous five tips in the series can be found here:
- Part 11, PullToRefreshListView Control
- Part 12, Working with Headings
- Part 13, the Loading… Control
- Part 14, RSS Parser
- Part 15, Markdown Parser
Intro
The Windows Community Toolkit v3 was a major update for the toolkit. In addition to adding and enhancing many of the extensions, animations, helpers and services, it has added several new controls.
- WebView for WPF and WinForms
- CameraPreview
- Microsoft Graph controls
- UniformGrid
- InfiniteCanvas
I will examine these new controls over the next several tips in the series. We will circle back to some of the other types of features in the toolkit later. Today, let's start with the InfiniteCanvas.
Using InfiniteCanvas
The new InfiniteCanvas control for UWP applications is a rich, polished and powerful control. Out of the box it supports inking, text entry & formatting, zooming, undo/redo and of course infinite scrolling (hence the name). You can also import and export the InfiniteCanvas contents as json.
Take a look at the InfiniteCanvas running in the latest version of the Windows Community Toolkit Sample App.
Notice that, like other text input controls in UWP apps, the text input in InfiniteCanvas supports spell checking. The toolbar on the control can be toggled on and off with the IsToolbarVisible property. You might want to bind that property so that it is only True when a particular part of your app has focus. Dropping the control into a Grid with the default functionality and a visible toolbar is as simple as:
<Grid>
<wctk:InfiniteCanvas IsToolbarVisible="True"/> </Grid>
The import/export functionality is performed by calling a pair of methods. ImportFromJson(string json) takes a string containing the data to display on the canvas. ExportAsJson() takes no parameters and returns a string with the json data representing the objects currently on the canvas. Exporting an empty canvas results in a json string with only an empty pair of square brackets.
Zooming bounds can be controlled with the MinZoomFactor and MaxZoomFactor properties. The Min can be set to a System.Double between 0.1 and 1 with a default of 0.25. The Max can be set to a double between 1 and 10 with the default being 4.
The other properties currently available on the control are CanvasHeight and CanvasWidth. These provide access to the size of the drawing surface, rather than the Height and Width of the InfiniteCanvas control itself. Go check out the documentation for a complete listing of the API surface of the control.
Wrap Up
Go check out the source code for InfiniteCanvas, download the latest toolkit NuGet packages, and give it a try in your UWP application today.
Happy coding!
Friday, May 18, 2018
UWP Tip #19 - The Windows Community Toolkit
Hello UWP developers!
We take a quick break from our UWP Community Toolkit tips series because the toolkit has been given a new name this month! The UWP Community Toolkit is now called the Windows Community Toolkit.
The new name is a reflection of the renewed focus of the project - enabling Windows developers to quickly build awesome applications for Windows 10. The scope of the toolkit will be broadening to encompass controls, components and helpers for UWP, WPF, WinForm, Xamarin.Form and more. Long story short, if you are building for Windows and can consume a .NET Standard library, the Windows Community Toolkit aims to help you succeed.
Everything has been renamed - the documentation and the GitHub repository for now, and soon the sample app.
The next major update of the toolkit (v3.0) is coming soon. If you take a look at the milestones on GitHub, there's a code freeze for 3.0 on May 23rd and the target date for the release is May 30th. I see some interesting features in the list of issues for this release including a dark theme for the sample app and an InfiniteCanvas control.
Go check out the announcement on the Windows Developer Blog from earlier this month to get all the information about the name change. As soon as the new release is out, I'll be back with some more tips and tricks for using the new controls and helpers.
If you want to help build the toolkit, check out the list of open issues and submit a PR!
Friday, March 30, 2018
UWP Tip #18 - UWP Community Toolkit - Part 15, Markdown Parser
- Part 10, OrbitView Control
- Part 11, PullToRefreshListView Control
- Part 12, Working with Headings
- Part 13, the Loading… Control
- Part 14, RSS Parser
Intro
As I mentioned in my last post, Part 14, the UWP Community Toolkit includes a pair of helper classes for parsing, one for parsing RSS data and the other for parsing markdown. Let's take a look into the Markdown Parser helper this time.Markdown Parser
The Markdown parser includes a helper class to take a markdown string, parse it into a Markdown Document and then render that document into your UWP controls with a Markdown Renderer.(Tip: The toolkit's MarkdownTextBlock also uses the MarkdownDocument and MarkdownRenderer classes. When you use the control, you can use this default renderer or set your own that overrides the MarkdownRendererBase.)The UWP Community Toolkit Sample App includes this simple example of the Markdown Parser in action.
In this example, you see the raw markdown "This is **Markdown**". That text was parsed into a MarkdownDocument. The document was then serialized to JSON and displayed in a TextBlock. Here is that code from the sample app:
private void UpdateMDResult()
{
var document = new MarkdownDocument();
document.Parse(RawMarkdown.Text);
var json = JsonConvert.SerializeObject(document, Formatting.Indented, new StringEnumConverter());
MarkdownResult.Text = json;
}
You can see that creating the document is as simple as instantiating a new MarkdownDocument and calling Parse with your raw text. Once you have a MarkdownDocument, you can very easily manipulate it to add, modify or remove individual blocks or elements. The document is essentially a list of markdown blocks. In fact, the sole property you need to be concerned with on MarkdownDocument is Blocks (an IList<MarkdownBlock>).Objects that derive from MarkdownBlock are MarkdownDocument or one of the following block types:
- CodeBlock
- HeaderBlock
- HorizontalRuleBlock
- LinkReferenceBlock
- ListBlock
- ParagraphBlock
- QuoteBlock
- TableBlock
- Id - A unique string id to identify the reference link.
- Tooltip - The link's tooltip to be displayed when rendered.
- Url - The target.
- Value - The text value to display for the link.
- Type - This is inherited from the MarkdownBlock base and would return the type of this particular block.
Wrap-Up
I encourage you to explore the Markdown Parser on MS Docs and GitHub when you have a chance. If you have any ideas to enhance this parser or any part of the toolkit, submit an issue or submit a pull request.Happy coding!










