代码改变世界

wpf学习笔记-更新数据源

  Clingingboy  阅读(985)  评论(1编辑  收藏  举报
此示例基于 wpf学习笔记-指定数据源


1.让对象实现INotifyPropertyChanged接口,以便属性更改发出通知

    public class Person : INotifyPropertyChanged
    
{
        
public Person() { }
        
public Person(string name, int age)
        
{
            
this.name = name;
            
this.age = age;
        }


        
string name;
        
public string Name
        
{
            
get return this.name; }
            
set
            
{
                
this.name = value;
                OnPropertyChanged(
"Name");
            }

        }


        
int age;
        
public int Age
        
{
            
get return this.age; }
            
set
            
{
                
this.age = value;
                OnPropertyChanged(
"Age");
            }

        }



        
public event PropertyChangedEventHandler PropertyChanged;

        
protected void OnPropertyChanged(string propName)
        
{
            
if (this.PropertyChanged != null)
            
{
                PropertyChanged(
thisnew PropertyChangedEventArgs(propName));
            }

        }


    }

2.xaml(略去布局)


        
<Label Content="{Binding Name}"></Label>
        
<Label Content="{Binding Age}"></Label>
        
<TextBox Text="{Binding Path=Name, Source={StaticResource Tom}}" />
        
<TextBox Text="{Binding Age}" 
            
/>
这里又出现了新的绑定语法,{Binding Path=Age}等价{Binding Age}

3.目标:
当更改目标属性的时候,更新数据源(更新以后则绑定的对象也发生变化,如更改TextBox的Text则Label的Content也发生变化)

4.设置更新数据源执行时间
通过设置Binding对象的UpdateSourceTrigger  来确定执行时间.

根据需要设置UpdateSourceTrigger 属性

编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示