1. 程式人生 > >WPF 利用元素繫結實現在一個視窗更新另一個視窗中Label的Content

WPF 利用元素繫結實現在一個視窗更新另一個視窗中Label的Content

首先建立一個數據類,我在裡面放了一個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: