在用户仍在打字时延迟方法调用

问题描述 投票:0回答:1

我的 MAUI XAML 页面中有一个搜索框,它调用 ViewModel 中的方法。它必须从数据库中过滤的数据量非常大,每次用户输入一封信时,都需要几秒钟的时间才能响应结果。我想延迟方法调用,例如。 1 秒,当用户停止输入(输入时间不超过 1 秒)时,它会调用过滤方法。

<!-- Search box -->
<Border StrokeThickness="0" Stroke="Transparent" Background="Transparent">
    <dxe:TextEdit EndIcon="search" PlaceholderText="Search" TextChangedCommand="{Binding FilterChangedCommand}" TextChangedCommandParameter="{Binding Source={RelativeSource Self}, Path=Text}" TextFontSize="14" TextVerticalAlignment="Center" BorderThickness="1" BoxPadding="20,6,10,6" CornerRadius="16" HeightRequest="35" Margin="15,10,15,10"/>
</Border>

我怎样才能在毛伊岛做到这一点?

c# xaml mvvm maui
1个回答
0
投票

这种技术称为去抖动。 .NET MAUI 社区工具包提供了一个即用型 Behavior,称为 UserStoppedTypingBehavior

示例如下所示:

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"
             x:Class="MyLittleApp.MainPage">
     
           <dxe:TextEdit EndIcon="search" PlaceholderText="Search" TextChangedCommand="{Binding FilterChangedCommand}" TextChangedCommandParameter="{Binding Source={RelativeSource Self}, Path=Text}" TextFontSize="14" TextVerticalAlignment="Center" BorderThickness="1" BoxPadding="20,6,10,6" CornerRadius="16" HeightRequest="35" Margin="15,10,15,10">
                <dxe:TextEdit.Behaviors>
                    <toolkit:UserStoppedTypingBehavior 
                        Command="{Binding SearchCommand}"
                        StoppedTypingTimeThreshold="1000"
                        MinimumLengthThreshold="3"
                        ShouldDismissKeyboardAutomatically="True" />
                </dxe:TextEdit.Behaviors>
            </dxe:TextEdit>
</ContentPage>

这假设您的

dxe:TextEdit
组件支持行为。如果没有,您可以查看 .NET MAUI Community Toolkit 代码并实现您自己的机制。

© www.soinside.com 2019 - 2024. All rights reserved.