我想建立一些倒数计数器。问题是我的解决方案在10秒后仅显示起始值10和最后一个值1。当然,我已经实现了INotifyPropertyChanged接口。关于该解决方案有什么建议吗?
<Button Content="Generuj" Command="{Binding ButtonStart}"></Button>
<TextBox Text="{Binding Counter, Mode=OneWay}"></TextBox>
private void ButtonStartClick(object obj)
{
for (int i = 10; i > 0; i--)
{
System.Threading.Thread.Sleep(1000);
Counter = i;
}
}
答案 0 :(得分:3)
使用Thread.Sleep,您将冻结GUI。尝试使用计时器来达到目的。 计时器将同时运行到您的GUI线程,因此不会冻结它。 另外,您将需要为计数器实现PropertyChanged事件 还要确保设置您的DataContext
//create a dependency property you can bind to (put into class)
public int Counter
{
get { return (int)this.GetValue(CounterProperty); }
set { this.SetValue(CounterProperty, value); }
}
public static readonly DependencyProperty CounterProperty =
DependencyProperty.Register(nameof(Counter), typeof(int), typeof(MainWindow), new PropertyMetadata(default(int)));
//Create a timer that runs one second and decreases CountDown when elapsed (Put into click event)
Timer t = new Timer();
t.Interval = 1000;
t.Elapsed += CountDown;
t.Start();
//restart countdown when value greater one (put into class)
private void CountDown(object sender, ElapsedEventArgs e)
{
if (counter > 1)
{
(sender as Timer).Start();
}
Counter--;
}
答案 1 :(得分:0)
您可以使用异步等待来引入轻量级延迟。
与计时器相比,它的主要优点是不存在使代表挂接并运行的风险。
在此视图模型中,我使用mvvmlight,但是任何ICommand实现都可以。
…..
using System.Threading.Tasks;
using GalaSoft.MvvmLight.CommandWpf;
namespace wpf_99
{
public class MainWindowViewModel : BaseViewModel
{
private int counter =10;
public int Counter
{
get { return counter; }
set { counter = value; RaisePropertyChanged(); }
}
private RelayCommand countDownCommand;
public RelayCommand CountDownCommand
{
get
{
return countDownCommand
?? (countDownCommand = new RelayCommand(
async () =>
{
for (int i = 10; i > 0; i--)
{
await Task.Delay(1000);
Counter = i;
}
}
));
}
}
视图不多,它绑定到Counter,当然:
<Grid>
<StackPanel>
<TextBlock Text="{Binding Counter}"/>
<Button Content="Count" Command="{Binding CountDownCommand}"/>
</StackPanel>
</Grid>
答案 2 :(得分:0)
您还可以在单独的线程中运行Counter
Task.Run(() =>
{
for (int i = 10; i > 0; i--)
{
Counter = i;
Thread.Sleep(1000);
}
});