Skip to content

feat: Enable Grid to dynamically switch layouts #4472

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -512,6 +512,9 @@
<Compile Include="SamplePages\FocusBehavior\FocusBehaviorPage.xaml.cs">
<DependentUpon>FocusBehaviorPage.xaml</DependentUpon>
</Compile>
<Compile Include="SamplePages\GridExtensions\GridExtensionsPage.xaml.cs">
<DependentUpon>GridExtensionsPage.xaml</DependentUpon>
</Compile>
<Compile Include="SamplePages\MetadataControl\MetadataControlPage.xaml.cs">
<DependentUpon>MetadataControlPage.xaml</DependentUpon>
</Compile>
@@ -647,6 +650,7 @@
<Content Include="SamplePages\Animations\Shadows\AnimatedCardShadowXaml.bind" />
<Content Include="SamplePages\KeyDownTriggerBehavior\KeyDownTriggerBehaviorXaml.bind" />
<Content Include="SamplePages\RichSuggestBox\RichSuggestBoxCode.bind" />
<Content Include="SamplePages\GridExtensions\GridExtensionsCode.bind" />
</ItemGroup>
<ItemGroup>
<Compile Include="App.xaml.cs">
@@ -991,6 +995,10 @@
<Content Include="SamplePages\MetadataControl\MetadataControlCode.bind">
<SubType>Designer</SubType>
</Content>
<Page Include="SamplePages\GridExtensions\GridExtensionsPage.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="SamplePages\MetadataControl\MetadataControlPage.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
<Page
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:ui="using:Microsoft.Toolkit.Uwp.UI"
xmlns:controls="using:Microsoft.Toolkit.Uwp.UI.Controls"
xmlns:triggers="using:Microsoft.Toolkit.Uwp.UI.Triggers"
mc:Ignorable="d">

<Page.Resources>
<Style TargetType="Border">
<Setter Property="Background" Value="Gray" />
<Setter Property="Padding" Value="4" />
</Style>
<Style TargetType="TextBlock">
<Setter Property="HorizontalAlignment" Value="Center"/>
</Style>
</Page.Resources>

<Grid VerticalAlignment="Top" Padding="16">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup>
<VisualState>
<VisualState.StateTriggers>
<triggers:CompareStateTrigger
Value="{Binding ElementName=Resizer, Path=(ui:FrameworkElementExtensions.ActualWidth)}"
Comparison="LessThanOrEqual"
To="360"/>
</VisualState.StateTriggers>
<VisualState.Setters>
<Setter Target="DynamicLayoutGrid.(ui:GridExtensions.ActiveLayout)" Value="Narrow"/>
</VisualState.Setters>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>


<Grid Grid.Row="1" Height="48">
<Grid.ColumnDefinitions>
<ColumnDefinition MinWidth="240" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Border
x:Name="Resizer"
ui:FrameworkElementExtensions.EnableActualSizeBinding="True"
Background="{StaticResource Brush-Brand-Color}">
<TextBlock TextWrapping="Wrap">
Resize to see the layout to be <LineBreak/>
switched dynamically.
</TextBlock>
</Border>
<controls:GridSplitter
HorizontalAlignment="Left"
Grid.Column="1"
Width="12"/>
</Grid>

<Grid
Grid.Row="2"
x:Name="DynamicLayoutGrid"
ui:GridExtensions.ActiveLayout="Normal"
ColumnSpacing="12"
RowSpacing="8"
BorderThickness="1"
BorderBrush="{ThemeResource SystemControlHighlightChromeHighBrush}"
HorizontalAlignment="Left"
Width="{Binding ElementName=Resizer, Path=(ui:FrameworkElementExtensions.ActualWidth)}"
Padding="8">
<!-- Declaratively define the possible layouts. -->
<!-- GridEx.Layouts is a dictionary of GridLayoutDefinition -->
<ui:GridExtensions.Layouts>
<ui:GridLayoutDefinition x:Key="Normal">
<!-- A GridLayoutDefinition consists of -->
<!-- row definitions, column definitions and an area definition -->
<ui:GridLayoutDefinition.RowDefinitions>
<RowDefinition Height="Auto"/>
</ui:GridLayoutDefinition.RowDefinitions>
<ui:GridLayoutDefinition.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</ui:GridLayoutDefinition.ColumnDefinitions>
<!-- Area definition just simply puts down -->
<!-- children names in desired order -->
Number Title Description
</ui:GridLayoutDefinition>
<ui:GridLayoutDefinition x:Key="Narrow">
<ui:GridLayoutDefinition.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</ui:GridLayoutDefinition.RowDefinitions>
<ui:GridLayoutDefinition.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</ui:GridLayoutDefinition.ColumnDefinitions>
Number Title; <!-- semicolon is used to separate differnt rows -->
Description Description <!-- row/column span is expressed by repeating the elment name -->
</ui:GridLayoutDefinition>
</ui:GridExtensions.Layouts>
<Border x:Name="Number" Width="32">
<TextBlock>1</TextBlock>
</Border>
<Border x:Name="Title">
<TextBlock>Lorem Ipsum</TextBlock>
</Border>
<Border x:Name="Description">
<TextBlock>Lorem ipsum dolor sit amet...</TextBlock>
</Border>
</Grid>
</Grid>
</Page>
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<Page x:Class="Microsoft.Toolkit.Uwp.SampleApp.SamplePages.GridExtensionsPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:ui="using:Microsoft.Toolkit.Uwp.UI"
mc:Ignorable="d">
<Grid />
</Page>
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using Windows.UI.Xaml.Controls;

namespace Microsoft.Toolkit.Uwp.SampleApp.SamplePages
{
public sealed partial class GridExtensionsPage : Page
{
public GridExtensionsPage()
{
this.InitializeComponent();
}
}
}
17 changes: 12 additions & 5 deletions Microsoft.Toolkit.Uwp.SampleApp/SamplePages/samples.json
Original file line number Diff line number Diff line change
@@ -1289,6 +1289,14 @@
"XamlCodeFile": "EnumValuesExtensionXaml.bind",
"CodeFile": "EnumValuesExtensionCode.bind",
"DocumentationUrl": "https://raw.githubusercontent.com/MicrosoftDocs/WindowsCommunityToolkitDocs/master/docs/extensions/EnumValuesExtension.md"
},
{
"Name": "GridExtensions",
"Type": "GridExtensionsPage",
"About": "Extensions to enable switching grid layouts dynamically",
"CodeUrl": "https://github.com/CommunityToolkit/WindowsCommunityToolkit/tree/main/Microsoft.Toolkit.Uwp.UI/Extensions/GridExtensions",
"XamlCodeFile": "GridExtensionsCode.bind",
"Icon": "/Assets/Helpers.png",
}
]
},
@@ -1302,7 +1310,7 @@
"About": "Demonstrate the properties and events of the Gaze Interaction library",
"XamlCodeFile": "GazeInteractionXaml.bind",
"CodeFile": "GazeInteractionCode.bind",
"CodeUrl" : "https://github.com/CommunityToolkit/WindowsCommunityToolkit/tree/main/Microsoft.Toolkit.Uwp.Input.GazeInteraction",
"CodeUrl": "https://github.com/CommunityToolkit/WindowsCommunityToolkit/tree/main/Microsoft.Toolkit.Uwp.Input.GazeInteraction",
"Icon": "/SamplePages/GazeInteraction/GazeInteraction.png",
"DocumentationUrl": "https://raw.githubusercontent.com/MicrosoftDocs/WindowsCommunityToolkitDocs/master/docs/gaze/GazeInteractionLibrary.md",
"ApiCheck": "Windows.Devices.Input.Preview.GazeInputSourcePreview"
@@ -1311,13 +1319,12 @@
"Name": "GazeTracing",
"Type": "GazeTracingPage",
"About": "Shows how to use the Windows 10 API for eye trackers",
"CodeUrl" : "https://github.com/CommunityToolkit/WindowsCommunityToolkit/tree/main/Microsoft.Toolkit.Uwp.Input.GazeInteraction",
"CodeUrl": "https://github.com/CommunityToolkit/WindowsCommunityToolkit/tree/main/Microsoft.Toolkit.Uwp.Input.GazeInteraction",
"XamlCodeFile": "GazeTracingXaml.bind",
"CodeFile": "GazeTracingCode.bind",
"Icon": "/SamplePages/GazeTracing/GazeTracing.png",
"ApiCheck": "Windows.Devices.Input.Preview.GazeInputSourcePreview",
"DocumentationUrl" : "https://raw.githubusercontent.com/MicrosoftDocs/WindowsCommunityToolkitDocs/master/docs/gaze/GazeInteractionLibrary.md"
"DocumentationUrl": "https://raw.githubusercontent.com/MicrosoftDocs/WindowsCommunityToolkitDocs/master/docs/gaze/GazeInteractionLibrary.md"
}
]
}
]
}]
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace Microsoft.Toolkit.Uwp.UI
{
/// <summary>
/// Provides ActiveLayout attached property for <see cref="Grid"/> element.
/// </summary>
public static partial class GridExtensions
{
/// <summary>
/// Attached <see cref="DependencyProperty"/> for binding <see cref="ActiveLayoutProperty"/> to a <see cref="Grid"/>
/// </summary>
public static readonly DependencyProperty ActiveLayoutProperty =
DependencyProperty.RegisterAttached("ActiveLayout", typeof(string), typeof(GridExtensions), new PropertyMetadata(null, OnActiveLayoutChanged));

/// <summary>
/// Gets the <see cref="ActiveLayoutProperty"/> associated with the specified <see cref="Grid"/>
/// </summary>
/// <param name="obj">The <see cref="Windows.UI.Xaml.Controls.Grid"/> from which to get the associated <see cref="ActiveLayoutProperty"/> value</param>
/// <returns>The <see cref="ActiveLayoutProperty"/> value associated with the <see cref="Grid"/> or null</returns>
public static string GetActiveLayout(Grid obj) => (string)obj.GetValue(ActiveLayoutProperty);

/// <summary>
/// Sets the <see cref="ActiveLayoutProperty"/> associated with the specified <see cref="Grid"/>
/// </summary>
/// <param name="obj">The <see cref="Grid"/> to associated the <see cref="ActiveLayoutProperty"/> to</param>
/// <param name="value">The <see cref="ActiveLayoutProperty"/> to bind to the <see cref="Grid"/></param>
public static void SetActiveLayout(Grid obj, string value) => obj.SetValue(ActiveLayoutProperty, value);

private static void OnActiveLayoutChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is Grid grid)
{
UpdateLayout(grid);
}
}
}
}
48 changes: 48 additions & 0 deletions Microsoft.Toolkit.Uwp.UI/Extensions/Grid/GridExtensions.Layouts.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Collections.Generic;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace Microsoft.Toolkit.Uwp.UI
{
using LayoutDictionary = System.Collections.Generic.IDictionary<string, Microsoft.Toolkit.Uwp.UI.GridLayoutDefinition>;

/// <summary>
/// Provides Layouts attached property for <see cref="Grid"/> element.
/// </summary>
public static partial class GridExtensions
{
/// <summary>
/// Attached <see cref="DependencyProperty"/> for binding <see cref="LayoutsProperty"/> to a <see cref="Grid"/>
/// </summary>
public static readonly DependencyProperty LayoutsProperty =
DependencyProperty.RegisterAttached("Layouts", typeof(LayoutDictionary), typeof(GridExtensions), new PropertyMetadata(null));

/// <summary>
/// Gets the <see cref="LayoutsProperty"/> associated with the specified <see cref="Grid"/>
/// </summary>
/// <param name="obj">The <see cref="Grid"/> from which to get the associated <see cref="LayoutsProperty"/> value</param>
/// <returns>The <see cref="LayoutsProperty"/> value associated with the <see cref="Grid"/> or null</returns>
public static LayoutDictionary GetLayouts(Grid obj)
{
var dictionary = (LayoutDictionary)obj.GetValue(LayoutsProperty);
if (dictionary is null)
{
dictionary = new Dictionary<string, GridLayoutDefinition>();
SetLayouts(obj, dictionary);
}

return dictionary;
}

/// <summary>
/// Sets the <see cref="LayoutsProperty"/> associated with the specified <see cref="Grid"/>
/// </summary>
/// <param name="obj">The <see cref="Grid"/> to associated the <see cref="LayoutsProperty"/> to</param>
/// <param name="value">The <see cref="LayoutsProperty"/> to bind to the <see cref="Grid"/></param>
public static void SetLayouts(Grid obj, LayoutDictionary value) => obj.SetValue(LayoutsProperty, value);
}
}
41 changes: 41 additions & 0 deletions Microsoft.Toolkit.Uwp.UI/Extensions/Grid/GridExtensions.Private.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace Microsoft.Toolkit.Uwp.UI
{
/// <summary>
/// Private methods on GridExtensions to enable dynamic layout switching capability.
/// </summary>
public partial class GridExtensions
{
private static readonly DependencyProperty LoadedCallbackRegisteredProperty =
DependencyProperty.RegisterAttached("LoadedCallbackRegistered", typeof(bool), typeof(GridExtensions), new PropertyMetadata(false));

private static void UpdateLayout(Grid grid)
{
if (grid.IsLoaded)
{
if (GetLayouts(grid).TryGetValue(GetActiveLayout(grid), out var layout))
{
layout.Apply(grid);
}
}
else if (!(bool)grid.GetValue(LoadedCallbackRegisteredProperty))
{
grid.SetValue(LoadedCallbackRegisteredProperty, true);
grid.Loaded += OnGridLoaded;
}
}

private static void OnGridLoaded(object sender, RoutedEventArgs args)
{
var grid = (Grid)sender;
grid.Loaded -= OnGridLoaded;
UpdateLayout(grid);
}
}
}
156 changes: 156 additions & 0 deletions Microsoft.Toolkit.Uwp.UI/Extensions/Grid/GridLayoutDefinition.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Linq;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Markup;

namespace Microsoft.Toolkit.Uwp.UI
{
/// <summary>
/// The data structure to define a possible grid layout.
/// </summary>
[ContentProperty(Name = "AreaDefinition")]
public class GridLayoutDefinition
{
private IDictionary<string, (int Row, int RowSpan, int Column, int ColumnSpan)> _cellProperties;

/// <summary>
/// Gets a list of ColumnDefinition objects defined for this layout.
/// </summary>
public List<ColumnDefinition> ColumnDefinitions { get; } = new List<ColumnDefinition>();

/// <summary>
/// Gets a list of RowDefinition objects defined for this layout.
/// </summary>
public List<RowDefinition> RowDefinitions { get; } = new List<RowDefinition>();

/// <summary>
/// Sets area definition for this layout.
/// </summary>
/// <remarks>
/// Aread definition string should list the <see cref="FrameworkElement.Name"/> of Grid elements in row-major order.
/// Elements in same row should be separated with whitespaces and rows should be separated with semicolons.
/// Row and column spans can be expressed by repeating element names.
/// </remarks>
/// <example>
/// A simple 2x3 grid layout:
/// .-----------.
/// | A | B | C |
/// |---|---|---|
/// | D | E | F |
/// '-----------'
/// A B C;
/// D E F;
///
/// A 3x3 grid layout where the first and third rows span 3 columns:
/// .-----------------------.
/// | header |
/// |------.--------.-------|
/// | left | center | right |
/// |------'--------'-------|
/// | footer |
/// '-----------------------'
/// header header header;
/// left center right;
/// footer footer footer;
///
/// A 3x3 grid layout with row span and column span.
/// .----------------------.
/// | | header |
/// | nav |--------.-------|
/// | | center | right |
/// |-----'--------'-------|
/// | footer |
/// '----------------------'
/// nav header header;
/// nav center right;
/// footer footer footer;
///
/// Incorrect usage:
/// A B C;
/// D A E;
/// will result in
/// .-----------.
/// | : B | C |
/// |...A...|---|
/// | D : | E |
/// '-----------'
/// Dotted lines are used to illustrate A, B and D children are overlapped.
/// This usage is not really invalid (it does not throw),
/// but this API is not expected to be used like this.
/// </example>
public string AreaDefinition
{
set => _cellProperties = ParseAreaDefinition(value);
}

internal void Apply(Grid grid)
{
ApplyRowColumnDefinitions(grid);
UpdateChildren(grid);
}

private static IDictionary<string, (int, int, int, int)> ParseAreaDefinition(string str)
{
var def = new Dictionary<string, (int Row, int RowSpan, int Column, int ColumnSpan)>();
var table = str
.Split(";", StringSplitOptions.RemoveEmptyEntries)
.Select(row => row.Trim().Split(" ", StringSplitOptions.RemoveEmptyEntries).Select(cell => cell.Trim()).ToList())
.ToList();
for (var i = 0; i < table.Count; ++i)
{
var tableRow = table[i];
for (var j = 0; j < tableRow.Count; ++j)
{
var childName = tableRow[j];
if (def.TryGetValue(childName, out var properties))
{
var (row, _, column, _) = properties;
def[childName] = (Row: row, RowSpan: i - row + 1, Column: column, ColumnSpan: j - column + 1);
}
else
{
def[childName] = (Row: i, RowSpan: 1, Column: j, ColumnSpan: 1);
}
}
}

return def;
}

private void ApplyRowColumnDefinitions(Grid grid)
{
grid.ColumnDefinitions.Clear();
foreach (var def in ColumnDefinitions)
{
grid.ColumnDefinitions.Add(def);
}

grid.RowDefinitions.Clear();
foreach (var def in RowDefinitions)
{
grid.RowDefinitions.Add(def);
}
}

private void UpdateChildren(Grid grid)
{
foreach (var child in grid.Children)
{
if (child is FrameworkElement element && _cellProperties.TryGetValue(element.Name, out var property))
{
child.SetValue(Grid.ColumnProperty, property.Column);
child.SetValue(Grid.RowProperty, property.Row);
child.SetValue(Grid.ColumnSpanProperty, property.ColumnSpan);
child.SetValue(Grid.RowSpanProperty, property.RowSpan);
}
}
}

}
}