WPF基础入门-Class6-WPF通知更改

WPF基础入门

Class6-WPF通知

1、显示页面:

    <Grid>
        <StackPanel>
            <TextBox Text="{Binding Name}">TextBox>
            <TextBox Text="{Binding Title}">TextBox>
            <Button Command="{Binding ShowCommand}" Content="Show">Button>
        StackPanel>
    Grid>

页面cs文件:

InitializeComponent();
this.DataContext = new WPF_Learn.Model.model_csdn();

2、新建一个ViewModelBase.cs文件

public class ViewModelBase : INotifyPropertyChanged
    {
    	//实现接口
        public event PropertyChangedEventHandler? PropertyChanged;
        //public void OnPropertyChanged(string propertyName)
        //{
        //    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        //}

        // 自动获取调用者的属性名,默认空,不需要传递参数
        public void OnPropertyChanged([CallerMemberName] string propertyName = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }

3、model文件:其中定义的NameTitlexaml文件中控件绑定一致

//继承ViewModelBase
class model_csdn : ViewModelBase
    {
        public model_csdn()
        {
            Name = "Ini_name";
            Title = "Ini_title";
            ShowCommand = new MyCommamd(show);
        }

        public MyCommamd ShowCommand { get; set; }
        public string name;
        public string title;
		
        public string Name
        {
            get { return name; }
            set
            {
                name = value;
                OnPropertyChanged();
            }
        }
        public string Title
        {
            get { return title; }
            set
            {
                title = value;
                OnPropertyChanged();
            }
        }

        public void show()
        {
            Name = "change name";
            Title = "change title";
            MessageBox.Show("change info");
        }
    }

运行效果:
WPF基础入门-Class6-WPF通知更改_第1张图片
WPF基础入门-Class6-WPF通知更改_第2张图片

你可能感兴趣的:(WPF基础入门,wpf)