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

时间:2013-07-05 20:21:42

标签: c# visual-studio-2010 xaml inotifypropertychanged

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

当我 删除 iNotifyPropertyChanged时,一切正常,文本框被绑定到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 64Bit上运行)

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

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

您是否遇到过这个问题?

1 个答案:

答案 0 :(得分:6)

您未正确地实施了该课程。你需要一个支持领域:

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

相关问题