在MainWindow中,我有一个名为jack的人的实例,并通过调用方法EnhanceElevation来增加Jacks的高度。
在NewWindow中,我有一个名为jill的人的实例,通过调用方法GrowthElevation我可以增加jills的仰角。
如何从NewWindow调用jack?IncreaseElevation,以便在MainWindow中增加jacks Elevation的值
我确信我缺少明显的东西。
public class Person: INotifyPropertyChanged
{
private int _elevation;
public string Name { get; set; }
public int Elevation
{
get { return _elevation; }
set
{
_elevation = value;
OnPropertyChanged("Elevation");
}
}
public void IncreaseElevation()
{
Elevation++;
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string property)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
MainWindow
public partial class MainWindow: Window
{
Person jack = new Person() { Name = "Jack", Elevation = 0 };
public MainWindow()
{
InitializeComponent();
this.DataContext = jack;
}
private void OpenNewWindow_Click(object sender, RoutedEventArgs e)
{
NewWindow newWindow = new NewWindow();
newWindow.Show();
}
private void IncreaseJacksElevation_Click(object sender, RoutedEventArgs e)
{
jack.IncreaseElevation();
}
}
NewWindow
public partial class NewWindow: Window
{
Person jill = new Person { Name ="Jill", Elevation = 0 };
public NewWindow()
{
InitializeComponent();
this.DataContext = jill;
}
private void IncreaseJillsElevation_Click(object sender, RoutedEventArgs e)
{
jill.IncreaseElevation();
}
private void IncreaseJacksElevation_Click(object sender, RoutedEventArgs e)
{
}
}
}
答案 0 :(得分:0)
有多种方法可以执行此操作,但是最终您只需要引用相同的Person
对象即可。一种方法是在NewWindow
的构造函数中提供该引用:
Person jack = null;
public NewWindow(Person _jack)
{
InitializeComponent();
this.DataContext = jill;
jack = _jack;
}
创建NewWindow
时:
NewWindow newWindow = new NewWindow(jack);
newWindow.Show();
然后在NewWindow
中您想要的任何地方,都有对同一Person
对象的可用类级引用:
private void IncreaseJacksElevation_Click(object sender, RoutedEventArgs e)
{
jack.IncreaseElevation();
}