LYT-WPF-MVVM框架中的INotifyPropertyChanged

参考文档:WPF MVVM框架中的INotifyPropertyChanged - 知乎 (zhihu.com)

INotifyPropertyChanged 接口用于通知视图或 ViewModel 绑定哪个属性无关紧要;它已更新。

让我们举个例子来理解这个接口。以一个 WPF 窗口为例,其中共有三个字段:名字、姓氏和全名。在这里,名字和姓氏文本框是可编辑的。因此,根据名字和姓氏的变化,我们必须自动更新全名。

使窗户设计图

 WPF 窗口的 XAML 代码如下

复制代码
<Window x:Class="MVVM_INotifyPropertyChanged.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow">  
    <Grid Width="400" Height="Auto" HorizontalAlignment="Center" VerticalAlignment="Stretch" Margin="20">  
        <Grid.RowDefinitions>  
            <RowDefinition Height="40" />  
            <RowDefinition Height="40" />  
            <RowDefinition Height="40" /> </Grid.RowDefinitions>  
        <Grid.ColumnDefinitions>  
            <ColumnDefinition Width="90" />  
            <ColumnDefinition/> </Grid.ColumnDefinitions>  
        <Label Grid.Row="0" Grid.Column="0" Content="First Name : "></Label>  
        <Label Grid.Row="1" Grid.Column="0" Content="Last Name : "></Label>  
        <Label Grid.Row="2" Grid.Column="0" Content="Full Name : "></Label>  
        <TextBox Grid.Row="0" Grid.Column="1"></TextBox>  
        <TextBox Grid.Row="1" Grid.Column="1"></TextBox>  
        <TextBox Grid.Row="2" Grid.Column="1"></TextBox>  
    </Grid>  
</Window>  
View Code
复制代码

现在,我们创建一个模型,它包含一个类调用人,它有3个属性“FirstName”,“LastName”,“FullName”。

复制代码
public class Person {  
    private string _fisrtname;  
    public string FirstName {  
        get {  
            return _fisrtname;  
        }  
        set {  
            _fisrtname = value;  
        }  
    }  
    private string _lastname;  
    public string LastName {  
        get {  
            return _lastname;  
        }  
        set {  
            _lastname = value;  
        }  
    }  
    private string _fullname;  
    public string FullName {  
        get {  
            return _fisrtname +" "+_lastname; ;  
        }  
        set {  
            _fullname = value;  
        }  
    }  
    public Person() {  
        _fisrtname = "Nirav";  
        _lastname = "Daraniya";  
    }  
}  
View Code
复制代码

 

posted on   Violin_Huang  阅读(16)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示