Sei sulla pagina 1di 11

UWP Cheat Sheet

***************

UWP-004 - What is XAML?


=======================================
XAML - XML Syntax, create instances of Classes that define the UI.

UWP-005 - Understanding Type Converters


=======================================
Type Converters - Convert literal strings in XAML into enumerations, instances of
classes, etc.

UWP-006 - Understanding Default Properties,


Complex Properties and the
Property Element Syntax
=======================================

Default Property ... Ex. sets Content property:


<Button>Click Me</Button>

Complex Properties - Break out a property into its own element syntax:

<Button Name="ClickMeButton"
HorizontalAlignment="Left"
Content="Click Me"
Margin="20,20,0,0"
VerticalAlignment="Top"
Click="ClickMeButton_Click"
Width="200"
Height="100"
>
<Button.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="Black" Offset="0"/>
<GradientStop Color="Red" Offset="1"/>
</LinearGradientBrush>
</Button.Background>
</Button>

UWP-007 - Understanding XAML Schemas


and Namespace Declarations
=======================================

Don't touch the schema stuff - it's necessary!

Schemas define rules for XAML, for UWP, for designer support, etc.

Namespaces tell XAML parser where to find the definition /


rules for a given element in the XAML.

UWP-008 - XAML Layout with Grids


========================================

Layout controls don't have a content property ...


they have a Chidren property of type UIElementCollection.

By embedding any control inside of a layout control,


you are implicitly calling the Add method of the Children
collection property.

<Grid Background="Black">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
</Grid>

Sizes expressed in terms of:

Explicit pixels - 100

Auto - use the largest value of elements it contains to define the width / height

* (Star Sizing) - Utilize all the available space

1* - Of all available space, give me 1 "share"


2* - Of all available space, give me 2 "shares"
3* - Of all available space, give me 3 "shares"

6 total shares ... 3* would be 50% of the available width / height.

Elements put themselves into rows and columns using attached property syntax:

...
...
<Button Grid.Row="0" />
</Grid>

- When referencing Rows and Columns ... 0-based.


- There's always one default implicit cell: Row 0, Column 0
- If not specified, element will be in the default cell

UWP-009 - XAML Layout with StackPanel


====================================

<StackPanel>
<TextBlock>Top</TextBlock>
<TextBlock>Bottom</TextBlock>
</StackPanel>

- Vertical Orientation by default.


- Left-to-right flow by default when Horizontal orientation.
- Most layouts will combine multiple layout controls.
- Grid will overlap controls. StackPanel will stack them.
UWP-017 - XAML Layout with the RelativePanel
====================================
It basically defines an area within which you can position and align child objects
-- in relation to each other
-- or in relation to the parent panel.

Controls use attached properties to position themselves.

Panel alignment relationships (AlignTopWithPanel, AlignLeftWithPanel, �) are


applied first.
Sibling alignment relationships (AlignTopWith, AlignLeftWith, �) are applied
second.
Sibling positional relationships (Above, Below, RightOf, LeftOf) are applied last.

<RelativePanel MinHeight="300" Grid.Row="1">


<Rectangle Name="RedRectangle" RelativePanel.AlignRightWithPanel="True" />
<Rectangle RelativePanel.LeftOf="RedRectangle" />
</RelativePanel>

UWP-018 - XAML Layout with the SplitPanel


====================================
The split view allows us to create a panel that
can be displayed or hidden.

We would use the SplitView to implement


hamburger navigation.

The are two parts to a SplitView:


1) The part that is hidden by default (Pane)
2) The part that is shown by default (Content)

You define other controls inside of the SplitView.Pane


and SplitView.Content.

<SplitView Name="MySplitView"
CompactPaneLength="50"
IsPaneOpen="False"
DisplayMode="CompactInline"
OpenPaneLength="200" >
<SplitView.Pane>
</SplitView.Pane>
<SplitView.Content>
</SplitView.Content>
</SplitView>

Inline � Panel completely covers content. When expanded, panel pushes content.

CompactInline � Pane covers most of the Content. When expanded, panel pushes
content.

Overlay � Panel completely covers content. When expanded, panel covers content.

CompactOverlay � Panel covers most of the content. When expanded, panel covers
content.

Open / Close Pane in C#:


MySplitView.IsPaneOpen = !MySplitView.IsPaneOpen;
UWP_019 - Working with Navigation
====================================
App > Window > Frame > MainPage

You can load pages into a child frame or into the root frame:

Frame.Navigate(typeof(Page2), additionalParameter);

You can retrieve additionalParameter on the page you navigated to:

protected override void OnNavigatedTo(NavigationEventArgs e)


{
value = (string)e.Parameter;
}

Traverse back stack (history):

if (Frame.CanGoBack) {
Frame.GoBack();
}

if (Frame.CanGoForward) {
Frame.GoForward();
}

Create a global variable by declaring a static internal field in the App class
definition.

UWP-020 - Common XAML Controls - Part 1


====================================

<CheckBox Name="MyCheckBox" Content="Agree?" Tapped="MyCheckBox_Tapped" />

CheckBoxResultTextBlock.Text = MyCheckBox.IsChecked.ToString();

<RadioButton Name="YesRadioButton" Content="Yes" GroupName="MyGroup"


checked="RadioButton_Checked" />
<RadioButton Name="NoRadioButton" Content="No" GroupName="MyGroup"
Checked="RadioButton_Checked" />

RadioButtonTextBlock.Text = (bool)YesRadioButton.IsChecked ? "Yes" : "No";

<ComboBox SelectionChanged="ComboBox_SelectionChanged" >


<ComboBoxItem Content="Fourth" />
<ComboBoxItem Content="Fifth" />
<ComboBoxItem Content="Sixth" IsSelected="True" />
</ComboBox>

if (ComboBoxResultTextBlock == null) return;


var combo = (ComboBox)sender;
var item = (ComboBoxItem)combo.SelectedItem;
ComboBoxResultTextBlock.Text = item.Content.ToString();
<ListBox Name="MyListBox" SelectionMode="Multiple"
SelectionChanged="ListBox_SelectionChanged">
<ListBoxItem Content="First" />
<ListBoxItem Content="Second" />
<ListBoxItem Content="Third" />
</ListBox>

var selectedItems = MyListBox.Items.Cast<ListBoxItem>()


.Where(p => p.IsSelected)
.Select(t => t.Content.ToString())
.ToArray();

ListBoxResultTextBlock.Text = string.Join(", ", selectedItems);

<Image Source="Assets/logo.png" Stretch="UniformToFill" />

<ToggleButton Name="MyToggleButton" Content="Premium Option" IsThreeState="True"


Click="MyToggleButton_Click" />

ToggleButtonResultTextBlock.Text = MyToggleButton.IsChecked.ToString();

<ToggleSwitch>
<ToggleSwitch.OffContent>
<TextBlock Text="I'm off right now." />
</ToggleSwitch.OffContent>
<ToggleSwitch.OnContent>
<TextBlock Text="I'm on!" />
</ToggleSwitch.OnContent>
</ToggleSwitch>

UWP-021 - Implementing a Simple Hamburger Navigation Menu


====================================
Jerry Nixon's Example: http://bit.do/hamburger-nav

Use Character Map to find the code to display icons using Segoe MDL5 Assets.

Hamburger: &#xE700;

Use ListBox and ListBoxItems for the navigation links inside of a SplitView.

UWP-025 - Common XAML Controls - Part 2


====================================

<TimePicker ClockIdentifier="12HourClock" />

<CalendarDatePicker PlaceholderText="choose a date" />

<CalendarView SelectionMode="Multiple"
SelectedDatesChanged="MyCalendarView_SelectedDatesChanged" />

private void MyCalendarView_SelectedDatesChanged(CalendarView sender,


CalendarViewSelectedDatesChangedEventArgs args)
{
var selectedDates = sender.SelectedDates.Select(p => p.Date.Month.ToString() +
"/" + p.Date.Day.ToString()).ToArray();
var values = string.Join(", ", selectedDates);
CalendarViewResultTextBlock.Text = values;
}

<Button Content="Flyout">
<Button.Flyout>
<Flyout x:Name="MyFlyout">

</Flyout>
</Button.Flyout>
</Button>

MyFlyout.Hide();

<Button Content="FlyoutMenu">
<Button.Flyout>
<MenuFlyout Placement="Bottom">
<MenuFlyoutItem Text="Item 1" />
<MenuFlyoutItem Text="Item 2" />
<MenuFlyoutSeparator />
<MenuFlyoutSubItem Text="Item 3">
<MenuFlyoutItem Text="Item 4" />
<MenuFlyoutSubItem Text="Item 5">
<MenuFlyoutItem Text="Item 6" />
<MenuFlyoutItem Text="Item 7" />
</MenuFlyoutSubItem>
</MenuFlyoutSubItem>
<MenuFlyoutSeparator />
<ToggleMenuFlyoutItem Text="Item 8" />
</MenuFlyout>
</Button.Flyout>
</Button>
<!-- You can apply this to anything ... ex. Image: -->
<!-- https://msdn.microsoft.com/en-us/library/windows/apps/xaml/dn308516.aspx -->

<AutoSuggestBox Name="MyAutoSuggestBox"
QueryIcon="Find"
PlaceholderText="Search"
TextChanged="MyAutoSuggestBox_TextChanged" />

private string[] selectionItems = new string[] { "Ferdinand", "Frank", "Frida",


"Nigel", "Tag", "Tanya", "Tanner", "Todd" };

private void MyAutoSuggestBox_TextChanged(AutoSuggestBox sender,


AutoSuggestBoxTextChangedEventArgs args)
{
var autoSuggestBox = (AutoSuggestBox)sender;
var filtered = selectionItems.Where(p =>
p.StartsWith(autoSuggestBox.Text)).ToArray();
autoSuggestBox.ItemsSource = filtered;
}

<Slider Maximum="100" Minimum="0" />


<ProgressBar Maximum="100" Value="{x:Bind MySlider.Value, Mode=OneWay}" />

<ProgressRing IsActive="True" />

UWP-026 - Working with the ScrollViewer


====================================

<ScrollViewer
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Auto">

</ScrollViewer>

You can put anything inside of it, however, don't put it inside of a StackPanel!

UWP-027 - Canvas and Shapes


====================================
Canvas allows you to do absolute positioning via attached properties.

<Line X1="10"
X2="200"
Y1="10"
Y2="10"
Stroke="Black"
Fill="Black"
StrokeThickness="5"
StrokeEndLineCap="Triangle" />

<Polyline Canvas.Left="150"
Canvas.Top="0"
Stroke="Black"
StrokeThickness="5"
Fill="Red"
Points="50,25 0,100 100,100 50,25"
StrokeLineJoin="Round"
StrokeStartLineCap="Round"
StrokeEndLineCap="Round" />

<Rectangle />
<Ellipse />

Canvas.ZIndex="100"

The higher the ZIndex, the higher in the stack it appears (covering what is below
it).

UWP-028 - XAML Styles


====================================

https://dev.windows.com/en-us/design

<Page.Resources>
<SolidColorBrush x:Key="MyBrush" Color="Brown" />
<Style TargetType="Button" x:Key="MyButtonStyle">
<Setter Property="Background" Value="Blue" />
<Setter Property="FontFamily" Value="Arial Black" />
<Setter Property="FontSize" Value="36" />
</Style>
</Page.Resources>

Binding: {StaticResource ResourceName}

<Button Content="OK" Style="{StaticResource MyButtonStyle}" />

Create Page or Application level resource dictionaries

<Application.Resources>
</Application.Resources>

Split up your styles into Resource Dictionary files:

<!-- Dictionary1.xaml -->


<ResourceDictionary>
<SolidColorBrush x:Key="brush" Color="Red"/>
</ResourceDictionary>

<Page>
<Page.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Dictionary1.xaml"/>
<ResourceDictionary Source="Dictionary2.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Page.Resources>

<TextBlock Foreground="{StaticResource SomeStyle}" Text="Hi" />


</Page>

UWP-029 - XAML Themes


====================================

http://bit.do/theme-resources

Put your mouse on a style, hit F12 to open generic.xaml

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">


<Rectangle Width="100" Height="100" Fill="{ThemeResource SystemAccentColor}" />
<Rectangle Width="50" Height="50" Fill="{ThemeResource SystemColorWindowColor}"
/>
</Grid>

<App RequestedTheme="Light">

High Contrast themes override styles.

Lots of different styles of system styles defined:


<TextBlock Text="page name" Style="{StaticResource HeaderTextBlockStyle}" />

Many styles defined in generic.xaml used BasedOn attribute ... and you can too!

UWP-037 - Utilizing the VisualStateManager to Create Adaptive Triggers


=================================================
VisualStateManager manages changes to XAML element attributes based on screen size
using Adaptive Triggers (MinWindowWidth, MinWindowHeight) and Setters (to change
target property values).

<VisualStateManager.VisualStateGroups>
<VisualStateGroup>
<VisualState x:Name="NarrowLayout">
<VisualState.StateTriggers>
<AdaptiveTrigger MinWindowWidth="0"/>
</VisualState.StateTriggers>
<VisualState.Setters>
<Setter Target="MyImage.Width" Value="200" />
<Setter Target="LayoutGrid.Background" Value="Blue" />
</VisualState.Setters>
</VisualState>
<VisualState x:Name="WideLayout">
<VisualState.StateTriggers>
<AdaptiveTrigger MinWindowWidth="600"/>
</VisualState.StateTriggers>
<VisualState.Setters>
<Setter Target="MyImage.Width" Value="200" />
<Setter Target="LayoutGrid.Background" Value="Blue" />
</VisualState.Setters>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>

UWP-038 - Working with Adaptive Layout


=======================================

http://bit.do/adaptive-ui

Use adaptive triggers to move StackPanels (filled with content) into different Grid
cells.

UWP-039 - Adaptive Layout with Device Specific Views


======================================================
Choose different versions of files to use based on the device running the app.

Example:

/DeviceFamily-Mobile
-- MainPage.xaml
/DeviceFamily-Desktop
-- MainPage.xaml

... or use a different file suffix for different device specific views:

MainPage.DeviceFamily-Mobile.xaml
MainPage.DeviceFamily-Desktop.xaml
http://bit.do/device-specific-views

UWP-40 - Data Binding to the GridView and ListView Controls


==========================================================
Bind to a List<T> where T is a POCO in your app (I put mine in the Models folder).

<Page
...
xmlns:data="using:xBindDataExample.Models">
<Page.Resources>
<DataTemplate x:DataType="data:Book" x:Key="BookDataTemplate">
<StackPanel HorizontalAlignment="Center">
<Image Source="{x:Bind CoverImage}" />
<TextBlock Text="{x:Bind Title}" />
<TextBlock Text="{x:Bind Author}" />
</StackPanel>
</DataTemplate>
</Page.Resources>
...
<GridView ItemsSource="{x:Bind Books}"
IsItemClickEnabled="True"
ItemClick="GridView_ItemClick"
ItemTemplate="{StaticResource BookDataTemplate}">
</GridView>
...

Code Behind
------------

public sealed partial class MainPage : Page


{
private List<Book> Books;

public MainPage()
{
this.InitializeComponent();
Books = BookManager.GetBooks();
}

private void GridView_ItemClick(object sender, ItemClickEventArgs e)


{
var book = (Book)e.ClickedItem;
ResultTextBlock.Text = "You selected " + book.Title;
}
}

UWP-041 - Keeping Data Controls Updated


with ObservableCollection
=======================================
If the contents of List<T> will change, make sure you use ObservableCollection<T>
instead!

UWP-042 - Utilizing User Controls as Data Templates


========================================
If you intend to combine the VisualStateManager with data bound controls, you will
need to put your Data Template code inside of a User Control, then create the
VisualStateManager code inside of the User Control.

1) Create a User Control.

2) Cut the Data Template out of the MainPage.xaml and copy it into the User
Control.

3) Reference the User Control from inside the Data Template:

<local:ContactTemplate HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />

4) Modify the contents of the User Control changing x:Bind statements to utilize
object.property notation:

<UserControl>
<StackPanel>
<Image Source="{x:Bind Contact.AvatarPath}" />
<TextBlock Text="{x:Bind Contact.FirstName}" />
<TextBlock Text="{x:Bind Contact.LastName}" />
</StackPanel>
</UserControl>

5) Add this in the User Control's Code Behind:


public Models.Contact Contact { get { return this.DataContext as
Models.Contact; } }

public ContactTemplate()
{
this.InitializeComponent();
this.DataContextChanged += (s, e) => Bindings.Update();
}

Potrebbero piacerti anche