谢谢。我希望我可以上传整个解决方案,因为我在打开这个问题之前已经准备好了。但我没有找到如何。我将在此处尽可能复制所有代码。
问题是:我认为这是 WPF 中一个容易复制的问题。我做了一个简单的代码版本来清楚地解释我的问题。示例中的容器“TwoPersons”有两个“Person”类实例。“当前”属性将是填充人员详细信息的详细信息面板的数据上下文。我可以使用 Current setter 方法在不同的版本之间跳转。我可以看到细节发生了相应的变化。问题是在切换和填充当前人的过程中,UI 控制更改(例如将男性更改为女性),然后更改会影响它绑定的 PREVIOUS 项目。persion 实例将被意外修改。在新实例绑定后,以前的实例似乎仍然与视图有联系。我怎样才能避免这种情况。任何帮助将不胜感激。
==================================================== =======================
这是 MainWindow.xaml.cs
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
TwoPersons twoPersons = new TwoPersons();
public MainWindow()
{
InitializeComponent();
DataContext = twoPersons;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
twoPersons.Next();
}
}
两个人的容器:
public class TwoPersons : INotifyPropertyChanged
{
Person p1 = new Person("Mary") { IsFemale = true };
Person p2 = new Person("Luis") { IsMale = true };
Person current;
public Person Current
{
get
{
if (current == null)
current = p1;
return current;
}
set
{
if (current != value)
{
current = value;
OnPropertyChanged("Current");
}
}
}
public void Next()
{
Current = Current == p1 ? p2 : p1;
}
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChangedEventArgs e = new PropertyChangedEventArgs(propertyName);
PropertyChanged(this, e);
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
人物类:
public class Person : INotifyPropertyChanged
{
public Person(string name)
{
this.name = name;
}
private string name;
public string Name
{
get { return name; }
}
public bool isMale;
public bool IsMale
{
get { return isMale; }
set
{
if (isMale != value)
{
isMale = value;
OnPropertyChanged("IsMale");
OnPropertyChanged("IsFemale");
OnPropertyChanged("Description");
}
}
}
public bool IsFemale
{
get { return !isMale; }
set { IsMale = !value; }
}
public string Description
{
get
{
return isMale ? "Male" : "Female";
}
}
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChangedEventArgs e = new PropertyChangedEventArgs(propertyName);
PropertyChanged(this, e);
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
主窗口 xaml
<Grid>
<StackPanel DataContext="{Binding Current}">
<TextBlock Text="{Binding Name}"></TextBlock>
<RadioButton IsChecked="{Binding IsMale}">Male</RadioButton>
<RadioButton IsChecked="{Binding IsFemale}">Female</RadioButton>
<TextBlock Text="{Binding Description}"></TextBlock>
<Button Click="Button_Click" Height="32">Next >></Button>
<TextBlock>Note. Mary should be alway a female! But it changes when navigating by clicking the button above </TextBlock>
</StackPanel>
</Grid>