Skip to content

Commit d9e8845

Browse files
author
msftbot[bot]
authored
Adding control size trigger (#3867)
<!-- 🚨 Please Do Not skip any instructions and information mentioned below as they are all required and essential to evaluate and test the PR. By fulfilling all the required information you will be able to reduce the volume of questions and most likely help merge the PR faster 🚨 --> <!-- 📝 It is preferred if you keep the "☑️ Allow edits by maintainers" checked in the Pull Request Template as it increases collaboration with the Toolkit maintainers by permitting commits to your PR branch (only) created from your fork. This can let us quickly make fixes for minor typos or forgotten StyleCop issues during review without needing to wait on you doing extra work. Let us help you help us! 🎉 --> ## Fixes # <!-- Add the relevant issue number after the "#" mentioned above (for ex: Fixes #1234) which will automatically close the issue once the PR is merged. --> <!-- Add a brief overview here of the feature/bug & fix. --> Adding a new visual state trigger which can be triggered based on a the width of a UI element rather than the width of the app's entire window. ## PR Type What kind of change does this PR introduce? <!-- Please uncomment one or more that apply to this PR. --> <!-- - Bugfix --> Feature <!-- - Code style update (formatting) --> <!-- - Refactoring (no functional changes, no api changes) --> <!-- - Build or CI related changes --> <!-- - Documentation content changes --> <!-- - Sample app changes --> <!-- - Other... Please describe: --> ## What is the current behavior? <!-- Please describe the current behavior that you are modifying, or link to a relevant issue. --> ## What is the new behavior? <!-- Describe how was this issue resolved or changed? --> ## PR Checklist Please check if your PR fulfills the following requirements: - [x] Tested code with current [supported SDKs](../readme.md#supported) - [x] Pull Request has been submitted to the documentation repository [instructions](..\contributing.md#docs). Link: https://github.com/MicrosoftDocs/WindowsCommunityToolkitDocs/pull/551<!-- docs PR link --> - [x] Sample in sample app has been added / updated (for bug fixes / features) - [x] Icon has been created (if new sample) following the [Thumbnail Style Guide and templates](https://github.com/windows-toolkit/WindowsCommunityToolkit-design-assets) - [x] New major technical changes in the toolkit have or will be added to the [Wiki](https://github.com/windows-toolkit/WindowsCommunityToolkit/wiki) e.g. build changes, source generators, testing infrastructure, sample creation changes, etc... - [x] Tests for the changes have been added (for bug fixes / features) (if applicable) - [x] Header has been added to all new source files (run *build/UpdateHeaders.bat*) - [x] Contains **NO** breaking changes <!-- If this PR contains a breaking change, please describe the impact and migration path for existing applications below. Please note that breaking changes are likely to be rejected within minor release cycles or held until major versions. --> ## Other information
2 parents 83a5bce + 8eba48b commit d9e8845

File tree

7 files changed

+368
-0
lines changed

7 files changed

+368
-0
lines changed

Microsoft.Toolkit.Uwp.SampleApp/Microsoft.Toolkit.Uwp.SampleApp.csproj

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1079,6 +1079,10 @@
10791079
<SubType>Designer</SubType>
10801080
<Generator>MSBuild:Compile</Generator>
10811081
</Content>
1082+
<Content Include="SamplePages\Triggers\ControlSizeTrigger.bind">
1083+
<SubType>Designer</SubType>
1084+
<Generator>MSBuild:Compile</Generator>
1085+
</Content>
10821086
<Page Include="SamplePages\Triggers\FullScreenModeStateTriggerPage.xaml">
10831087
<Generator>MSBuild:Compile</Generator>
10841088
<SubType>Designer</SubType>
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
<Page
2+
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
3+
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
4+
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
5+
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
6+
xmlns:triggers="using:Microsoft.Toolkit.Uwp.UI.Triggers"
7+
mc:Ignorable="d">
8+
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
9+
10+
<VisualStateManager.VisualStateGroups>
11+
<VisualStateGroup>
12+
<VisualState>
13+
<VisualState.StateTriggers>
14+
<triggers:ControlSizeTrigger
15+
TargetElement="{Binding ElementName=ParentGrid}"
16+
MinWidth="400"
17+
MaxWidth="500"/>
18+
</VisualState.StateTriggers>
19+
<VisualState.Setters>
20+
<Setter Target="ResizingText.FontSize" Value="20"/>
21+
</VisualState.Setters>
22+
</VisualState>
23+
</VisualStateGroup>
24+
</VisualStateManager.VisualStateGroups>
25+
26+
<StackPanel VerticalAlignment="Center" Width="500">
27+
<Grid
28+
x:Name="ParentGrid"
29+
Width="{Binding Value, ElementName=Slider, Mode=OneWay}"
30+
Height="50"
31+
Background="Blue"/>
32+
<TextBlock
33+
x:Name="ResizingText"
34+
FontSize="12"
35+
Text="Windows Community Toolkit"
36+
HorizontalAlignment="Center"/>
37+
<Slider
38+
x:Name="Slider"
39+
Minimum="0"
40+
Maximum="500" />
41+
</StackPanel>
42+
</Grid>
43+
</Page>

Microsoft.Toolkit.Uwp.SampleApp/SamplePages/XamlOnlyPage.xaml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
<triggers:RegexStateTrigger x:Key="RegexStateTrigger" />
3232
<triggers:UserHandPreferenceStateTrigger x:Key="UserHandPreferenceStateTrigger" />
3333
<triggers:UserInteractionModeStateTrigger x:Key="UserInteractionModeStateTrigger" />
34+
<triggers:ControlSizeTrigger x:Key="ControlSizeTrigger" />
3435
<behaviors:StartAnimationAction x:Key="StartAnimationAction" />
3536
<behaviors:KeyDownTriggerBehavior x:Key="KeyDownTriggerBehavior" />
3637
<behaviors:AutoSelectBehavior x:Key="AutoSelectBehavior" />

Microsoft.Toolkit.Uwp.SampleApp/SamplePages/samples.json

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -920,6 +920,15 @@
920920
"Icon": "/Assets/Helpers.png",
921921
"DocumentationUrl": "https://raw.githubusercontent.com/MicrosoftDocs/WindowsCommunityToolkitDocs/master/docs/helpers/Triggers.md"
922922
},
923+
{
924+
"Name": "ControlSizeTrigger",
925+
"Subcategory": "State Triggers",
926+
"About": "Enables a state if the target control meets the specified size",
927+
"CodeUrl": "https://github.com/CommunityToolkit/WindowsCommunityToolkit/blob/master/Microsoft.Toolkit.Uwp.UI/Triggers/ControlSizeTrigger.cs",
928+
"XamlCodeFile": "/SamplePages/Triggers/ControlSizeTrigger.bind",
929+
"Icon": "/Assets/Helpers.png",
930+
"DocumentationUrl": "https://raw.githubusercontent.com/MicrosoftDocs/WindowsCommunityToolkitDocs/master/docs/helpers/Triggers.md"
931+
},
923932
{
924933
"Name": "IsEqualStateTrigger",
925934
"Subcategory": "State Triggers",
Lines changed: 185 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,185 @@
1+
// Licensed to the .NET Foundation under one or more agreements.
2+
// The .NET Foundation licenses this file to you under the MIT license.
3+
// See the LICENSE file in the project root for more information.
4+
5+
using Windows.UI.Xaml;
6+
7+
namespace Microsoft.Toolkit.Uwp.UI.Triggers
8+
{
9+
/// <summary>
10+
/// A conditional state trigger that functions
11+
/// based on the target control's width or height.
12+
/// </summary>
13+
public class ControlSizeTrigger : StateTriggerBase
14+
{
15+
/// <summary>
16+
/// Gets or sets a value indicating
17+
/// whether this trigger will be active or not.
18+
/// </summary>
19+
public bool CanTrigger
20+
{
21+
get => (bool)GetValue(CanTriggerProperty);
22+
set => SetValue(CanTriggerProperty, value);
23+
}
24+
25+
/// <summary>
26+
/// Identifies the <see cref="CanTrigger"/> DependencyProperty.
27+
/// </summary>
28+
public static readonly DependencyProperty CanTriggerProperty = DependencyProperty.Register(
29+
nameof(CanTrigger),
30+
typeof(bool),
31+
typeof(ControlSizeTrigger),
32+
new PropertyMetadata(true, (d, e) => ((ControlSizeTrigger)d).UpdateTrigger()));
33+
34+
/// <summary>
35+
/// Gets or sets the max width at which to trigger.
36+
/// This value is exclusive, meaning this trigger
37+
/// could be active if the value is less than MaxWidth.
38+
/// </summary>
39+
public double MaxWidth
40+
{
41+
get => (double)GetValue(MaxWidthProperty);
42+
set => SetValue(MaxWidthProperty, value);
43+
}
44+
45+
/// <summary>
46+
/// Identifies the <see cref="MaxWidth"/> DependencyProperty.
47+
/// </summary>
48+
public static readonly DependencyProperty MaxWidthProperty = DependencyProperty.Register(
49+
nameof(MaxWidth),
50+
typeof(double),
51+
typeof(ControlSizeTrigger),
52+
new PropertyMetadata(double.PositiveInfinity, (d, e) => ((ControlSizeTrigger)d).UpdateTrigger()));
53+
54+
/// <summary>
55+
/// Gets or sets the min width at which to trigger.
56+
/// This value is inclusive, meaning this trigger
57+
/// could be active if the value is >= MinWidth.
58+
/// </summary>
59+
public double MinWidth
60+
{
61+
get => (double)GetValue(MinWidthProperty);
62+
set => SetValue(MinWidthProperty, value);
63+
}
64+
65+
/// <summary>
66+
/// Identifies the <see cref="MinWidth"/> DependencyProperty.
67+
/// </summary>
68+
public static readonly DependencyProperty MinWidthProperty = DependencyProperty.Register(
69+
nameof(MinWidth),
70+
typeof(double),
71+
typeof(ControlSizeTrigger),
72+
new PropertyMetadata(0.0, (d, e) => ((ControlSizeTrigger)d).UpdateTrigger()));
73+
74+
/// <summary>
75+
/// Gets or sets the max height at which to trigger.
76+
/// This value is exclusive, meaning this trigger
77+
/// could be active if the value is less than MaxHeight.
78+
/// </summary>
79+
public double MaxHeight
80+
{
81+
get => (double)GetValue(MaxHeightProperty);
82+
set => SetValue(MaxHeightProperty, value);
83+
}
84+
85+
/// <summary>
86+
/// Identifies the <see cref="MaxHeight"/> DependencyProperty.
87+
/// </summary>
88+
public static readonly DependencyProperty MaxHeightProperty = DependencyProperty.Register(
89+
nameof(MaxHeight),
90+
typeof(double),
91+
typeof(ControlSizeTrigger),
92+
new PropertyMetadata(double.PositiveInfinity, (d, e) => ((ControlSizeTrigger)d).UpdateTrigger()));
93+
94+
/// <summary>
95+
/// Gets or sets the min height at which to trigger.
96+
/// This value is inclusive, meaning this trigger
97+
/// could be active if the value is >= MinHeight.
98+
/// </summary>
99+
public double MinHeight
100+
{
101+
get => (double)GetValue(MinHeightProperty);
102+
set => SetValue(MinHeightProperty, value);
103+
}
104+
105+
/// <summary>
106+
/// Identifies the <see cref="MinHeight"/> DependencyProperty.
107+
/// </summary>
108+
public static readonly DependencyProperty MinHeightProperty = DependencyProperty.Register(
109+
nameof(MinHeight),
110+
typeof(double),
111+
typeof(ControlSizeTrigger),
112+
new PropertyMetadata(0.0, (d, e) => ((ControlSizeTrigger)d).UpdateTrigger()));
113+
114+
/// <summary>
115+
/// Gets or sets the element whose width will observed
116+
/// for the trigger.
117+
/// </summary>
118+
public FrameworkElement TargetElement
119+
{
120+
get => (FrameworkElement)GetValue(TargetElementProperty);
121+
set => SetValue(TargetElementProperty, value);
122+
}
123+
124+
/// <summary>
125+
/// Identifies the <see cref="TargetElement"/> DependencyProperty.
126+
/// </summary>
127+
/// <remarks>
128+
/// Using a DependencyProperty as the backing store for TargetElement. This enables animation, styling, binding, etc.
129+
/// </remarks>
130+
public static readonly DependencyProperty TargetElementProperty = DependencyProperty.Register(
131+
nameof(TargetElement),
132+
typeof(FrameworkElement),
133+
typeof(ControlSizeTrigger),
134+
new PropertyMetadata(null, OnTargetElementPropertyChanged));
135+
136+
/// <summary>
137+
/// Gets a value indicating whether the trigger is active.
138+
/// </summary>
139+
public bool IsActive { get; private set; }
140+
141+
private static void OnTargetElementPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
142+
{
143+
((ControlSizeTrigger)d).UpdateTargetElement((FrameworkElement)e.OldValue, (FrameworkElement)e.NewValue);
144+
}
145+
146+
// Handle event to get current values
147+
private void OnTargetElementSizeChanged(object sender, SizeChangedEventArgs e)
148+
{
149+
UpdateTrigger();
150+
}
151+
152+
private void UpdateTargetElement(FrameworkElement oldValue, FrameworkElement newValue)
153+
{
154+
if (oldValue != null)
155+
{
156+
oldValue.SizeChanged -= OnTargetElementSizeChanged;
157+
}
158+
159+
if (newValue != null)
160+
{
161+
newValue.SizeChanged += OnTargetElementSizeChanged;
162+
}
163+
164+
UpdateTrigger();
165+
}
166+
167+
// Logic to evaluate and apply trigger value
168+
private void UpdateTrigger()
169+
{
170+
if (TargetElement == null || !CanTrigger)
171+
{
172+
SetActive(false);
173+
return;
174+
}
175+
176+
bool activate = MinWidth <= TargetElement.ActualWidth &&
177+
TargetElement.ActualWidth < MaxWidth &&
178+
MinHeight <= TargetElement.ActualHeight &&
179+
TargetElement.ActualHeight < MaxHeight;
180+
181+
IsActive = activate;
182+
SetActive(activate);
183+
}
184+
}
185+
}
Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
// Licensed to the .NET Foundation under one or more agreements.
2+
// The .NET Foundation licenses this file to you under the MIT license.
3+
// See the LICENSE file in the project root for more information.
4+
5+
using System;
6+
using Microsoft.Toolkit.Uwp;
7+
using Microsoft.Toolkit.Uwp.UI.Triggers;
8+
using Microsoft.VisualStudio.TestTools.UnitTesting;
9+
using System.Threading.Tasks;
10+
using Windows.UI.Xaml.Controls;
11+
12+
namespace UnitTests.UWP.UI.Triggers
13+
{
14+
[TestClass]
15+
[TestCategory("Test_ControlSizeTrigger")]
16+
public class Test_ControlSizeTrigger : VisualUITestBase
17+
{
18+
[DataTestMethod]
19+
[DataRow(450, 450, true)]
20+
[DataRow(400, 400, true)]
21+
[DataRow(500, 500, false)]
22+
[DataRow(399, 400, false)]
23+
[DataRow(400, 399, false)]
24+
public async Task ControlSizeTriggerTest(double width, double height, bool expectedResult)
25+
{
26+
await App.DispatcherQueue.EnqueueAsync(async () =>
27+
{
28+
Grid grid = CreateGrid(width, height);
29+
await SetTestContentAsync(grid);
30+
var trigger = new ControlSizeTrigger();
31+
32+
trigger.TargetElement = grid;
33+
trigger.MaxHeight = 500;
34+
trigger.MinHeight = 400;
35+
trigger.MaxWidth = 500;
36+
trigger.MinWidth = 400;
37+
38+
Assert.AreEqual(expectedResult, trigger.IsActive);
39+
});
40+
}
41+
42+
[DataTestMethod]
43+
[DataRow(400, 400, true)]
44+
[DataRow(400, 399, false)]
45+
public async Task ControlSizeMinHeightTriggerTest(double width, double height, bool expectedResult)
46+
{
47+
await App.DispatcherQueue.EnqueueAsync(async () =>
48+
{
49+
Grid grid = CreateGrid(width, height);
50+
await SetTestContentAsync(grid);
51+
var trigger = new ControlSizeTrigger();
52+
53+
trigger.TargetElement = grid;
54+
trigger.MinHeight = 400;
55+
56+
Assert.AreEqual(expectedResult, trigger.IsActive);
57+
});
58+
}
59+
60+
[DataTestMethod]
61+
[DataRow(399, 400, false)]
62+
[DataRow(400, 400, true)]
63+
public async Task ControlSizeMinWidthTriggerTest(double width, double height, bool expectedResult)
64+
{
65+
await App.DispatcherQueue.EnqueueAsync(async () =>
66+
{
67+
Grid grid = CreateGrid(width, height);
68+
await SetTestContentAsync(grid);
69+
var trigger = new ControlSizeTrigger();
70+
71+
trigger.TargetElement = grid;
72+
trigger.MinWidth = 400;
73+
74+
Assert.AreEqual(expectedResult, trigger.IsActive);
75+
});
76+
}
77+
78+
[DataTestMethod]
79+
[DataRow(450, 450, false)]
80+
[DataRow(450, 449, true)]
81+
public async Task ControlSizeMaxHeightTriggerTest(double width, double height, bool expectedResult)
82+
{
83+
await App.DispatcherQueue.EnqueueAsync(async () =>
84+
{
85+
Grid grid = CreateGrid(width, height);
86+
await SetTestContentAsync(grid);
87+
var trigger = new ControlSizeTrigger();
88+
89+
trigger.TargetElement = grid;
90+
trigger.MaxHeight = 450;
91+
92+
Assert.AreEqual(expectedResult, trigger.IsActive);
93+
});
94+
}
95+
96+
[DataTestMethod]
97+
[DataRow(450, 450, false)]
98+
[DataRow(449, 450, true)]
99+
public async Task ControlSizeMaxWidthTriggerTest(double width, double height, bool expectedResult)
100+
{
101+
await App.DispatcherQueue.EnqueueAsync(async () =>
102+
{
103+
Grid grid = CreateGrid(width, height);
104+
await SetTestContentAsync(grid);
105+
var trigger = new ControlSizeTrigger();
106+
107+
trigger.TargetElement = grid;
108+
trigger.MaxWidth = 450;
109+
110+
Assert.AreEqual(expectedResult, trigger.IsActive);
111+
});
112+
}
113+
114+
private Grid CreateGrid(double width, double height)
115+
{
116+
var grid = new Grid()
117+
{
118+
Height = height,
119+
Width = width
120+
};
121+
122+
return grid;
123+
}
124+
}
125+
}

UnitTests/UnitTests.UWP/UnitTests.UWP.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -255,6 +255,7 @@
255255
<Compile Include="UI\Extensions\Test_VisualExtensions.cs" />
256256
<Compile Include="UI\Person.cs" />
257257
<Compile Include="UI\Test_AdvancedCollectionView.cs" />
258+
<Compile Include="UI\Triggers\Test_ControlSizeTrigger.cs" />
258259
<Compile Include="VisualUITestBase.cs" />
259260
</ItemGroup>
260261
<ItemGroup>

0 commit comments

Comments
 (0)