为什么在 WPF 中将 INotifyPropertyChanged 与绑定一起使用?

2024-04-03

我注意到,几乎我在互联网上找到的有关绑定的每个示例都有一个类(绑定到另一个属性),该类继承 INotifyPropertyChanged 接口并在该类属性的 set 部分中使用一个方法。

我尝试从绑定示例中删除该部分,其工作原理与该方法相同。

这是例子。我已经对其进行了更改,因此它将是双向绑定模式,并在消息框中显示更改后的属性。

我这样做只是为了玩一下绑定,但现在我真的不知道为什么使用该接口

XAML:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="30"/>
            <RowDefinition Height="30"/>
            <RowDefinition Height="30"/>
            <RowDefinition Height="30"/>
            <RowDefinition Height="30"/>
            <RowDefinition Height="40"/>
            <RowDefinition Height="30"/>
            <RowDefinition Height="30"/>
            <RowDefinition Height="30"/>
            <RowDefinition Height="30"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="30"/>
            <ColumnDefinition Width="30"/>
            <ColumnDefinition Width="30"/>
            <ColumnDefinition Width="30"/>
            <ColumnDefinition Width="30"/>
            <ColumnDefinition Width="100"/>
            <ColumnDefinition Width="30"/>
            <ColumnDefinition Width="30"/>
            <ColumnDefinition Width="30"/>
            <ColumnDefinition Width="30"/>
            <ColumnDefinition Width="30"/>
            <ColumnDefinition Width="30"/>
            <ColumnDefinition Width="30"/>
            <ColumnDefinition Width="30"/>
            <ColumnDefinition Width="30"/>
            <ColumnDefinition Width="30"/>
        </Grid.ColumnDefinitions>
        <Button Grid.Row="5" Grid.Column="5" Name="btnBinding" Click="btnBinding_Click" Width="100" Height="30">
            <Grid HorizontalAlignment="Left" VerticalAlignment="Center">
                <Grid.RowDefinitions>
                    <RowDefinition Height="25"/>
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="50"/>
                    <ColumnDefinition Width="50"/>
                </Grid.ColumnDefinitions>
                <TextBox Name="txtBinding" Width="30" Height="25" HorizontalAlignment="Left"/> 
                <Label Grid.Column="1" Content="Bind"/>
            </Grid>
        </Button>
        <Button Grid.Column="5" Grid.Row="6" Name="btnMessage" Click="btnMessage_Click" Content="MessageBox"/>
        <Button Grid.Column="5" Grid.Row="4" Name="btnChangeproperty" Click="btnChangeproperty_Click" Content="Change Property"/>
    </Grid>
</Window>

Main.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        Binding bind;
        MyData mydata;
        public MainWindow()
        {
            InitializeComponent();
        }

        private void btnBinding_Click(object sender, RoutedEventArgs e)
        {
            mydata = new MyData("T");
            bind = new Binding("MyDataProperty")
            {
                Source = mydata,
                Mode = BindingMode.TwoWay
            };

            txtBinding.SetBinding(TextBox.TextProperty, bind);
        }

        private void btnMessage_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show(mydata.MyDataProperty);
        }

        private void btnChangeproperty_Click(object sender, RoutedEventArgs e)
        {
            mydata.MyDataProperty = "New Binding";
        }
    }
}

我的数据类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;

namespace WpfApplication1
{
    public class MyData 
    {
        private string myDataProperty;

        public MyData() { }

        public MyData(DateTime dateTime)
        {
            myDataProperty = "Last bound time was " + dateTime.ToLongTimeString();
        }

        public MyData(string teste)
        {
            myDataProperty = teste;
        }

        public String MyDataProperty
        {
            get { return myDataProperty; }
            set
            {
                myDataProperty = value;
                OnPropertyChanged("MyDataProperty");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(string info)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(info));
            }
        }
    }
}

你不需要INotifyPropertyChanged如果您只想使用绑定write到该财产(正如您所发现的),但您确实需要它,以便您可以告诉其他人写入属性并相应更新显示的值。

要了解我在说什么,请在窗口中添加一个按钮,单击该按钮会直接更改绑定属性的值(not绑定到该属性的 UI 元素的相应属性)。和INotifyPropertyChanged,当您单击按钮时,您将看到 UI 自行更新为新值;如果没有它,用户界面仍将显示“旧”值。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么在 WPF 中将 INotifyPropertyChanged 与绑定一起使用? 的相关文章

随机推荐

  • 自定义错误处理和康康舞

    我正在尝试实现自定义错误处理以及使用 CanCan 当用户到达不允许访问的区域时 会引发 CanCan AccessDenied 错误 并且应将其发送到根 url 相反 rescue from Exception 捕获 CanCan Acc
  • Lucene 搜索具有特定字段的文档?

    Lucene Net 有没有办法查询包含特定字段的文档 假设我的一些文档有 食物 字段 而有些则没有 我想找到所有包含字段 foo 的文档 无论 foo 的值是什么 我该怎么做呢 它是某种 TermQuery 吗 尝试 foo TO 应该适
  • 如何使用java仅获取mongodb中文档的objectId

    我只想从 mongodb 中获取具有匹配条件的 objectId 我可以使用 db 对象和游标方法获取它 但我在这里使用 mongo 客户端 不知道该怎么做 感谢您 MongoClient client new MongoClient lo
  • 返回 JSON 和文件

    如何返回 JSON 响应和文件响应 现在我这样做 runNumber A0001 response None try response make response Line One r nLine Two r n response head
  • 按相等性对对象进行分组

    我有一个对象集合 我想使用如下所示的方法来比较它们的相等性 bool AreEqual MyObject O1 MyObject O2 将所有相同对象分组的最性能友好的方式是什么 显而易见的答案是将每个对象与集合中的所有其他对象进行比较 但
  • 减去数据框中的两列

    我的 df 看起来如下 Index Country Val1 Val2 Val10 1 Australia 1 3 5 2 Bambua 12 33 56 3 Tambua 14 34 58 我想从每个国家 地区的 Val1 中减去 Val
  • SQL Server 中 IsInteger 的最佳等效项

    在 SQL Server 2000 2005 2008 中确定字段值是否为整数的最佳方法是什么 IsNumeric 对于多种不太可能转换为整数的格式返回 true 示例包括 15 000 和 15 1 您可以使用类似的语句 但这似乎只适用于
  • Docker 检查格式检索端口映射[重复]

    这个问题在这里已经有答案了 我想使用 docker Inspection 检索映射到容器的端口 我发现了类似的内容 docker inspect format NetworkSettings Ports containerid Output
  • 如何进行空合并提交(忽略更改)?

    自动化 CI 工具合并了来自release to master 但是来自发布分支的一些提交应该被忽略 让我们考虑以下示例 发布分支包含两个修复 fix 1应该被忽略并且fix 2应该合并到master base merge fix 2 ma
  • jboss 7 oracle数据源配置

    我目前正在从 jboss 4 3 迁移到 jboss 7 1 1 Final 我正在尝试配置 Oracle 数据源 但它不起作用 以下是我为设置 Oracle 数据源所做的操作 1 下载ojdbc6 11 jar并将其放在文件夹 JBOSS
  • 使用 bootstrap 4 对 3 列进行排序和堆叠

    I have this structure in bootstrap columns And I want you to change to a lower resolution be ordered as follows 我在这里找到了如
  • PHP 致命错误:未找到“COM”类

    将 PHP 升级到 v 5 5 1 后 我收到此错误 Fatal error Class COM not found in C inetpub wwwroot ndsystems database engine mssql engine p
  • 如何使用 nth-child 为具有行跨度的表格设置样式?

    我有一张表 其中一行使用行跨度 所以 table tr td td td td td td tr tr td td td td td td tr tr td td td td tr tr td td td td td td tr table
  • 如何在 Java 中将日期从 MM/YYYY 转换为 MM/DD/YYYY

    我想将日期从 MM YYYY 转换为 MM DD YYYY 我如何使用 Java 中的 SimpleDateFormat 来做到这一点 注 DD可以是该月的开始日期 请浏览http download oracle com javase 1
  • ggplot 中的概率热图

    I asked this question https stackoverflow com questions 7305803 plot probability heatmap hexbin with different sized bin
  • 如何获取 Linux/UNIX 上当前网络接口吞吐量统计信息? [关闭]

    Closed 这个问题不符合堆栈溢出指南 help closed questions 目前不接受答案 MRTG 等工具提供特定接口 例如 eth0 上当前网络利用率的网络吞吐量 带宽图表 如何在 Linux UNIX 上的命令行返回该信息
  • 禁用一个函数的返回值优化

    struct X void a void b X foo void u void v foo 在汇编器中实现 i386 X 类型的返回值的地址作为隐藏参数传递给 foo 如果使用 O0 编译测试代码 则代码将按预期工作 如果使用 O3 编译
  • AH01626:要求全部授权授权结果:已授权

    我在我的网站上运行 apache 2 4 6 我不断在我的 apache 错误日志中看到这条消息一遍又一遍地重复 Tue Nov 10 01 42 40 659710 2015 authz core debug pid 10727 mod
  • 开源 BPM 工具(如 Activiti、bonita)和 Windows Workflow Foundation 之间有什么区别

    我试图找到一个基于asp net的免费开源BPM工具 但不幸的是我没有找到这样的工具 但最近我读到一篇关于Windows Workflow Foundation的文章 那么它是否提供了类似于开源BPM工具如Activiti bonita J
  • 为什么在 WPF 中将 INotifyPropertyChanged 与绑定一起使用?

    我注意到 几乎我在互联网上找到的有关绑定的每个示例都有一个类 绑定到另一个属性 该类继承 INotifyPropertyChanged 接口并在该类属性的 set 部分中使用一个方法 我尝试从绑定示例中删除该部分 其工作原理与该方法相同 这