WPF绑定属性

 

1.创建model类

model类要继承接口INotifyPropertyChanged,用于通知客户端属性值已更改

    public class StudentModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public void RaisePropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        private string name = "";
        public string Name
        {
            get => name; set { name = value; RaisePropertyChanged("Name"); }
        }
    }

  

2.创建ViewModel类

    public class Window2ViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        public void RaisePropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        private StudentModel studentModel = new StudentModel();
        public StudentModel StudentModel
        {
            get => studentModel; set { studentModel = value; RaisePropertyChanged("studentModel"); }

        }
    }

  

3.View绑定属性

(1)在Window2.xaml.cs中为DataContext赋值

    /// <summary>
    /// Window2.xaml 的交互逻辑
    /// </summary>
    public partial class Window2 : Window
    {
        public Window2()
        {
            InitializeComponent();
            this.DataContext = new Window2ViewModel();
        }
    }

(2)在Window2.xaml中绑定数据

    <Grid>
        <TextBox HorizontalAlignment="Left" Height="23" Margin="243,160,0,0" TextWrapping="Wrap" Text="{Binding StudentModel.Name,UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Top" Width="120"/>
        <Label HorizontalAlignment="Left" Height="23" Margin="243,208,0,0" Content="{Binding StudentModel.Name}" VerticalAlignment="Top" Width="120"/>
    </Grid>

  

4.效果

在1中输入,2中会及时显示

 

posted @ 2019-07-23 18:09  翻白眼的哈士奇  阅读(2741)  评论(0编辑  收藏  举报