WPF 是一种静态标记语言。据我所知,纯 XAML 中没有可用的机制来提供您正在寻找的功能。
如果您想避免直接使用计时器,您可以使用 Tasks 将其抽象出来。
主窗口 XAML:
<Window x:Class="AsyncTimer.MainWindow"
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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:AsyncTimer"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Label Content="{Binding CurrentTime}"></Label>
</Grid>
</Window>
后面的代码:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new CurrentTimeViewModel();
}
}
public class CurrentTimeViewModel : INotifyPropertyChanged
{
private string _currentTime;
public CurrentTimeViewModel()
{
UpdateTime();
}
private async void UpdateTime()
{
CurrentTime = DateTime.Now.ToString("G");
await Task.Delay(1000);
UpdateTime();
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public string CurrentTime
{
get { return _currentTime; }
set { _currentTime = value; OnPropertyChanged(); }
}
}
这可能是您将获得的更简洁且肯定是“现代” WPF 之一。