gpt4 book ai didi

xaml - 使用 progressBar xamarin 表单显示计时器

转载 作者:行者123 更新时间:2023-12-04 14:25:03 25 4
gpt4 key购买 nike

如何添加一个漂亮的计时器
xaml:

 <ProgressBar x:Name="progressBar" Grid.Row="2" Grid.ColumnSpan="5"
IsVisible="true"
Progress="0.0"
WidthRequest="300"
HeightRequest="20"
VerticalOptions="Center"
HorizontalOptions="Center">
</ProgressBar>

代码背后:

progressBar.Progress = 0;
await progressBar.ProgressTo(1.0, 90000, Easing.Linear);

最佳答案

您可以使用计时器来增加 ProgressBar:

var updateRate = 1000 / 30f; // 30Hz
double step = updateRate / (2 * 30 * 1000f);
Device.StartTimer(TimeSpan.FromMilliseconds(updateRate), () =>
{
if (progressBar.Progress < 100)
{
Device.BeginInvokeOnMainThread(() => progressBar.Progress += step );
return true;
}
return false;
});

然后您可以使用 IValueConverter 将进度转换为分钟:秒样式格式:

public class CountDownConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
double time = 0;
double.TryParse(parameter.ToString(), out var totalTime);
double.TryParse(value.ToString(), out var progress);
time = progress <= double.Epsilon ? totalTime : (totalTime - (totalTime * progress));
var timeSpan = TimeSpan.FromMilliseconds(time);
return $"{timeSpan.Minutes:00;00}:{timeSpan.Seconds:00;00}";
}

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}

将它与 XAML 结合在一起:

<Label
BindingContext="{x:Reference progressBar}"
Text = "{Binding Progress, StringFormat='{0:P0}'}"
HorizontalOptions ="Center"
FontSize="20"
FontFamily = "Helvetica Neue"
TextColor ="Red" />
<ProgressBar x:Name="progressBar"
IsVisible="true"
Progress="0.0"
WidthRequest="300"
HorizontalOptions="Center">
</ProgressBar>
<Label Text="{Binding Source={x:Reference progressBar},
Path=Progress,
Converter={StaticResource countDownTime},
ConverterParameter=120000}}"
HorizontalOptions ="Center"
FontSize="20"
FontFamily = "Helvetica Neue"
TextColor = "Red" />

输出:

enter image description here

更新:

您必须定义一个 ResourceDictionary 来创建和命名 CountDownConverter 类的实例,以便您可以在 XAML 中引用它:

<ContentPage.Resources>
<ResourceDictionary>
<tools:CountDownConverter x:Key="countDownTime"/>
</ResourceDictionary>
</ContentPage.Resources>

tools: 命名空间引用基于包含 CountDownConverter 的 C# 命名空间和程序集。我在一个单独的库中有一堆这样的 IValueConverter 类,因此我的 xmlns:tools 看起来像:

xmlns:tools="clr-namespace:Converters;assembly=Converters"

回复:Resource Dictionaries

关于xaml - 使用 progressBar xamarin 表单显示计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47733152/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com