从另一个类调用实例化方法

时间:2019-03-03 12:38:55

标签: c# wpf

在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)
    {

    }
}

}

1 个答案:

答案 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();
}