【发布时间】:2018-02-14 14:17:17
【问题描述】:
我想用 xamarin 表单制作一个简单的秒表应用程序。
界面如下:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:testvb"
x:Class="testvb.MainPage">
<StackLayout>
<Label Text="{Binding LabelText}">
<Label.BindingContext>
<local:GetDuration/>
</Label.BindingContext>
<Label.GestureRecognizers>
<TapGestureRecognizer
Command="{Binding TapCommand}">
</TapGestureRecognizer>
</Label.GestureRecognizers>
</Label>
<Label Text="{Binding SWDuration}">
<Label.BindingContext>
<local:GetDuration/>
</Label.BindingContext>
</Label>
<Label Text="{Binding StartTimeText}">
<Label.BindingContext>
<local:GetDuration/>
</Label.BindingContext>
</Label>
</StackLayout>
</ContentPage>
还有 c# 类:
namespace testvb
{
class GetDuration : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
static string labeltext = "START";
static string starttimetext = "Timer hasn't been started";
ICommand tapCommand;
static Stopwatch hstopwatch = new Stopwatch();
string swduration;
public GetDuration()
{
tapCommand = new Command(OnTapped);
this.SWDuration = hstopwatch.Elapsed.ToString();
Device.StartTimer(TimeSpan.FromSeconds(1), () =>
{
this.SWDuration = hstopwatch.Elapsed.ToString();
return true;
});
}
public ICommand TapCommand
{
get
{
return tapCommand;
}
}
void OnTapped (object s)
{
if(LabelText == "START")
{
LabelText = "STOP";
StartTimeText = DateTime.Now.ToString();
hstopwatch.Restart();
}
else
{
LabelText = "START";
StartTimeText = "Timer has been stopped";
hstopwatch.Stop();
hstopwatch.Reset();
}
}
public string LabelText
{
get
{
return labeltext;
}
set
{
if(labeltext != value)
{
labeltext = value;
if(PropertyChanged!=null)
{
PropertyChanged(this, new PropertyChangedEventArgs("LabelText"));
}
}
}
}
public string SWDuration
{
get
{
return swduration;
}
set
{
if(swduration!=value)
{
swduration = value;
if(PropertyChanged!=null)
{
PropertyChanged(this, new PropertyChangedEventArgs("SWDuration"));
}
}
}
}
public string StartTimeText
{
get
{
return starttimetext;
}
set
{
if (starttimetext != value)
{
starttimetext = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("StartTimeText"));
}
}
}
}
}
}
从界面开始,我有一个标签(单击它时在开始和停止之间切换),一个显示持续时间的标签,以及一个显示秒表启动时间的标签。
xamarin android 模拟器上的输出:_
- 标签(开始/停止)效果很好
- 持续时间也可以显示在显示屏上,但最后一个标签不会改变。
- 其值保持在“计时器尚未启动”
我不明白为什么它不能用于最后一个标签,因为主体与第一个标签(开始/停止)相同。如果有人能指出我误解的地方或我的代码在哪一部分做错了,我会感谢你的。
谢谢。
【问题讨论】:
-
首先我建议将所有变量设置为实例级别。我还建议向我们展示 xaml.cs 文件。
-
@NickPolideropoulos 我读了一些文章,按变量实例级别,你的意思是我不应该使用静态?
-
如果答案有效,那么您应该使用复选标记将其标记为已接受。这样做会对每个人都有帮助。
-
@dev1998 完成 :)
标签: c# xaml xamarin.forms