wpf - WPF 中 PropertyChanged UpdataSourceTrigger 的奇怪行为

标签 wpf binding propertychanged updatesourcetrigger

我有一个这样的实体:

public class Person
{
    public string Name { get; set; }

    public Person()
    {
        Name = "Godspeed";
    }
}

然后我在 XAML 中有三个文本框和一个按钮:
<Window x:Class="WpfApplication19.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication19"
        Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
        <local:Person />
    </Window.DataContext>
    <StackPanel>
        <TextBox Text="{Binding Name,UpdateSourceTrigger=PropertyChanged}" />
        <TextBox Text="{Binding Name,UpdateSourceTrigger=PropertyChanged}" />
        <TextBox Text="{Binding Name,UpdateSourceTrigger=PropertyChanged}" />
        <Button Click="Button_Click">Click</Button>
    </StackPanel>
</Window>

奇怪的是,实体“Person”并没有实现 INotifyPropertyChanged,但是当一个文本框发生变化时,它会修改源(Person 对象),但是我们没有引发属性更改事件而是其余两个文本框自动改变。

当按钮点击时,我们直接通过如下代码更新源代码:
((Person)DataContext).Name = "Godspeed";

它不更新。所以我的想法是,如果Person类实现了INotifyPropertyChanged,这种行为是正常的,但是现在该类没有实现接口(interface),但它也更新了接口(interface)。如果您有任何线索,请告诉我原因。谢谢。

最佳答案

原因是PropertyDescriptor,看下面的线程,
有人问同样的问题:How does the data binding system know when a property is changed?

这里有两个答案

I think the magic lies in the binding system's use of PropertyDescriptor (SetValue presumably raises a ValueChanged - the PropertyDescriptor is likely shared, while the events are raised on a per-object basis).



I'm not at Microsoft, but I can confirm it. If PropertyDescriptor is used to update the value, as it will be, then relevant change notifications are automatically propagated.



编辑
您可以通过命名 Person 来验证这一点。数据上下文对象
<Window.DataContext>
    <local:Person x:Name="person"/>
</Window.DataContext>

并将以下代码添加到 MainWindow Actor
public MainWindow()
{
    InitializeComponent();

    PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(person);
    PropertyDescriptor nameProperty = properties[0];
    nameProperty.AddValueChanged(person, OnPropertyChanged);
}
void OnPropertyChanged(object sender, EventArgs e)
{
    MessageBox.Show("Name Changed");
}

一旦您更改了三个 TextBox 中任何一个的值,您将最终进入事件处理程序 OnPropertyChanged。

关于wpf - WPF 中 PropertyChanged UpdataSourceTrigger 的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7037141/

相关文章:

C# - 如何根据对另一个属性 (ObservableCollection) 的更改来更改属性的值?

c# - 组合框触发空选择

wpf - 如何在WPF中创建一个允许鼠标事件通过的半透明窗口

c# - Winforms MVVM GridView 数据绑定(bind)

c# - 使用 ItemsSource 和 ItemTemplate 的 WPF 列表框

c# - ObservableCollection PropertyChanged 事件

c# - 什么是依赖属性?它的用途是什么?

c# - 将项目动态添加到 WPF 组合框,然后在某些事件上重置值

html - 如果来自 HTML 绑定(bind)的对象的 *ngFor Let 对象返回空数组,如何显示占位符

c# - 使模拟在更改时触发 PropertyChanged