zoukankan      html  css  js  c++  java
  • 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中会及时显示

  • 相关阅读:
    基础 ByteBuffer 和 ByteBuf
    Java 堆栈,内存分配理解
    JVM 调优参数设置
    Python 安装 matplotlib 制图
    UOJ#207. 共价大爷游长沙
    ORM学习 一 : JPA JDBC
    常见的Web攻击手段
    《Kubernetes权威指南第2版》学习(二)一个简单的例子
    五 pyJWT使用
    《Kubernetes权威指南第2版》学习(一) Kubernetes是什么
  • 原文地址:https://www.cnblogs.com/yaosj/p/11233538.html
Copyright © 2011-2022 走看看