背景
WINUI不提供原生的Trigger支持,推荐使用VisualStateManager进行操作;然对于从WPF转WINUI的开发人员而言,经常会想用Trigger解决问题,鉴于此社区推出了CommunityToolkit.WinUI.Triggers以支持Trigger的使用。
使用方法
1.项目中引入CommunityToolkit.WinUI.Triggers Nuget包。
当前最新稳定版本为8.0.240109,具体见下图:
2. 在Page中引入CommunityToolkit.WinUI
xmlns:triggers="using:CommunityToolkit.WinUI"
3. 在需要的地方编写相应的Trigger
如编写一个校验是否为邮箱的校验,以下为示例截图:
xml中代码如下:
<Page x:Class="TriggersExperiment.Samples.RegexStateTriggerSample"
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:local="using:TriggersExperiment.Samples"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:triggers="using:CommunityToolkit.WinUI"
mc:Ignorable="d">
<Grid>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup>
<VisualState x:Name="validEmail">
<VisualState.StateTriggers>
<!-- Note: Simple example RegEx, see our IsEmail string extension using emailregex.com for official RFC 5322 support -->
<triggers:RegexStateTrigger Expression="^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$"
Options="IgnoreCase"
Value="{Binding Text, ElementName=emailTextBox, Mode=OneWay}" />
</VisualState.StateTriggers>
<VisualState.Setters>
<Setter Target="emailStatus.Text" Value="This is a valid email" />
<Setter Target="emailStatus.Foreground" Value="{ThemeResource SystemFillColorSuccessBrush}" />
<Setter Target="submitButton.IsEnabled" Value="true" />
</VisualState.Setters>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<StackPanel MaxWidth="400">
<TextBox x:Name="emailTextBox"
HorizontalAlignment="Stretch"
Header="Enter an email" />
<TextBlock x:Name="emailStatus"
Margin="0,4,0,24"
Foreground="{ThemeResource SystemFillColorCriticalBrush}"
Style="{StaticResource CaptionTextBlockStyle}"
Text="Not a valid email" />
<Button x:Name="submitButton"
Content="Submit"
IsEnabled="False" />
</StackPanel>
</Grid>
</Page>
后台代码如下:
using CommunityToolkit.WinUI;
namespace TriggersExperiment.Samples;
[ToolkitSample(id: nameof(RegexStateTriggerSample), "RegexStateTrigger", description: $"A sample for showing how to create and use a {nameof(RegexStateTrigger)}.")]
public sealed partial class RegexStateTriggerSample : Page
{
public RegexStateTriggerSample()
{
this.InitializeComponent();
}
}
注:以上示例来源于Github。
实现原理
可以看到Trigger的实现还是借助于VisualState实现,只是自定义了一些相应的校验规则而已。以后再做相应介绍。
参考链接:
GitHub - CommunityToolkit/Windows: Collection of controls for WinUI 2, WinUI 3, and Uno Platform developers. Simplifies and demonstrates common developer tasks building experiences for Windows with .NET.