首先创建一个数据类,我在里面放了一个string类型的counter
public class Data: INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private string counter; public string Counter { get { return counter; } set { //值改变 if (counter != value) { counter = value; //触发改变事件 if (PropertyChanged != null) { //通知前台UI更新 PropertyChanged(this,new PropertyChangedEventArgs("Counter")); } } } } }
然后在前台绑定,我把Label的Content和counter绑定,这样当counter的值有所变化是,label.Content也会跟着一起变
<Window.Resources> <local:Data x:Key="LabelData"/> </Window.Resources> <Grid DataContext="{StaticResource ResourceKey=LabelData}"> <Label x:Name="label" Content="{Binding Path=Counter}" HorizontalAlignment="Left" Margin="150,20,30,40" VerticalAlignment="Center"/> <Label x:Name="label1" Content="Counter:" HorizontalAlignment="Left" Margin="50,20,30,40" VerticalAlignment="Center"/> </Grid>
点击Main Window的Start按钮后,后台的countr就开始自增,Timer的Counter的值也会随着counter的改变而改变。
Demo: