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

WPF基础入门

Class6-WPF通知

1、显示页面:

html 复制代码
    <Grid>
        <StackPanel>
            <TextBox Text="{Binding Name}"></TextBox>
            <TextBox Text="{Binding Title}"></TextBox>
            <Button Command="{Binding ShowCommand}" Content="Show"></Button>
        </StackPanel>
    </Grid>

页面cs文件:

cs 复制代码
InitializeComponent();
this.DataContext = new WPF_Learn.Model.model_csdn();

2、新建一个ViewModelBase.cs文件

csharp 复制代码
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文件中控件绑定一致

csharp 复制代码
//继承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");
        }
    }

运行效果:

相关推荐
上海物联网6 小时前
Prism Regions-自定义区域适配器实现开发者将任意 WPF 控件转换为可动态加载视图的区域容器
面试·wpf
Aevget1 天前
DevExpress WPF中文教程:Data Grid - 如何绑定到有限制的自定义服务(四)?
wpf·界面控件·devexpress·ui开发·.net 10
棉晗榜1 天前
wpf DataGrid控制列是否显示,DataGrid列不会触发Visibility的转换器
wpf
超级种码1 天前
Redis:Redis高可用——副本、哨兵和集群
数据库·redis·wpf
棉晗榜1 天前
wpf给Border添加闪烁边框
wpf
Derrick_itRose1 天前
DevExpress笔记WPF(2)Data Editors and Controls(基础编辑器)
笔记·编辑器·wpf
He BianGu1 天前
【笔记】WPF的Binding中AsyncState的使用方式
笔记·wpf
曹天骄2 天前
Cloudflare KV 使用教程(基于 Wrangler 项目)
wpf
摘星编程2 天前
Flutter for OpenHarmony 实战:Dialog 对话框详解
flutter·wpf
ou.cs2 天前
WPF TreeView 自动展开所有节点:附加行为(Attached Behavior)保姆级实现教程
c#·.net·wpf