[英]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.