[英]Implementing iNotifyPropertyChanged for a simple Person class crashes VisualStudio XAML designer
我有这个特殊的问题。 我所拥有的只是我的XAML中的单个文本框,绑定到Person
类。 当我在Person
类中实现iNotifyPropertyChanged
,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发生了变化....
你遇到过这个问题吗?
你不正确地实现了这个类。 你需要一个支持领域:
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
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.