为简单的Person类实现iNotifyPropertyChanged会导致VisualStudio XAML设计器崩溃

本文关键字:XAML VisualStudio 崩溃 简单 Person iNotifyPropertyChanged 实现 | 更新日期: 2023-09-27 18:21:09

我遇到了这个特殊的问题。我所拥有的只是XAML中的一个文本框,绑定到一个Person类。当我在Person类中实现iNotifyPropertyChanged时,Visual Studio XAML设计器会崩溃,如果我只是运行该项目,我会得到StackOverflow异常。

当我removeiNotifyPropertyChanged时,一切正常,并且文本框被绑定到Person类中的FirstName字段。

这是我的XAML,没什么特别的,只是一个数据绑定的文本框

<Window x:Class="DataBinding_WithClass.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"
        xmlns:c="clr-namespace:DataBinding_WithClass">
    <Grid x:Name="myGrid" >
        <Grid.Resources>
            <c:Person x:Key="MyPerson" />            
        </Grid.Resources>
        <Grid.DataContext>
            <Binding Source="{StaticResource MyPerson}"/>
        </Grid.DataContext>
        <TextBox Text="{Binding FirstName}" Width="150px"/>
    </Grid>
</Window>

这是我的Person类,在同一个项目中:

public class Person: INotifyPropertyChanged
    {
        public string FirstName
        {
            get
            { return FirstName; }
            set
            {
                FirstName = value;
                OnPropertyChanged("FirstName");
            }
        }            
       public event PropertyChangedEventHandler PropertyChanged;
        // Create the OnPropertyChanged method to raise the event 
        protected void OnPropertyChanged(string name)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(name));
            }
        }  
    }

我试过

重新启动Visual Studio 2012(在windows 7 Home Premium 64位上运行)

开始一个新的空白项目-相同的问题

这太奇怪了,没有iNotifyPropertyChanged,一切都很好,但我的文本框不会得到更新,因为我的*Person*类中的FirstName发生了更改。。。。

你遇到这个问题了吗?

为简单的Person类实现iNotifyPropertyChanged会导致VisualStudio XAML设计器崩溃

您不正确地实现了该类。您需要一个后备字段:

private string firstName;
public string FirstName
{
     get { return this.firstName; }
     set
     {
         if(this.firstName != value)
         {
            this.firstName = value; // Set field
            OnPropertyChanged("FirstName");
         }
     }
}

现在,getter正在获取自身,setter设置属性本身,这两者都将导致StackOverflowException