using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WpfApplication2 { /// <summary> /// 繼承INotifyPropertyChanged接口,當值發生改變時,向客戶端發出通知。 /// </summary> public class SliderClass : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; public void NotifyPropertyChanged(string propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } private double _length=0.0; public double Length { get { return _length; } set { _length = value; NotifyPropertyChanged("Length"); } } } }
在mainpage中定義兩個Slider。ide
<Grid x:Name="grid"> <Grid.RowDefinitions> <RowDefinition Height="120*"/> <RowDefinition Height="199*"/> </Grid.RowDefinitions> <Slider Value="{Binding Path=Length,Mode=TwoWay}" Margin="10,0,-10,71"/> <Slider Value="{Binding Path=Length,Mode=TwoWay}" Grid.Row="1" Margin="0,47,0,123"></Slider> </Grid>
在後臺new一個SliderClass做爲Grid的數據源。會發現第一個Slider會帶動第二個Slider變化,反之也成立。this
本文主要理解INotifyPropertyChanged接口和實現雙向綁定基礎以及如何調用NotifyPropertyChanged。spa