本文介绍了尝试将MainWindow继承到子类中,但得到系统stackoverflow的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在事件处理程序方法中通过引用发送变量?

How can I send variables by reference in an event handler method?

我尝试使用委托将其发送到另一个函数,该函数包含我所需的变量,并且该函数有效.但是,它创建了变量的副本,并且我无法从委托函数中更改主类中的值.然后,我考虑过将函数移到一个类上,并将所有变量存储在该类中,以便可以获取和设置它们.但是,由于它是一个类并且不继承主类,因此无法找到WPF/XAML对象.我曾尝试继承mainclass,但是因为我正在mainclass中创建类,并且它有效地继承了自身,所以陷入了一个无法逃脱的循环.

I've tried using a delegate to send it to another function that holds the variable I needed and it works. However, it creates a copy of the variable and and I can't change the value in the main class from the delegate function. I've then thought of moving the function to a class and store all the variables in the class so they can get and set. However, because it's a class and doesn't inherit the mainclass the WPF/XAML objects can't be found. I've tried inheriting the mainclass but because I'm creating the class inside the mainclass and that it is inheriting itself effectively it gets in a loop it can't escape.

public partial class MainWindow : Window
{

    public class Program : MainWindow
    {
        public string Word { get; set; }

        public void WhenPressed_1(object sender, RoutedEventArgs e)
        {
            lable_1.Content = Word;
        }
    }
    public MainWindow()
    {            
        InitializeComponent();

        Program test = new Program();
        Button_1.Click += delegate (object sender, RoutedEventArgs e) { test.WhenPressed_1(sender, e); };
    }       
}

这行代码是test = new Program();坏了

It's at the line Program test = new Program(); it breaks.

推荐答案

您可以将MainWindow对象传递给程序类并更改所需的值

You can pass MainWindow object to the program class and change the value you want

   public partial class MainWindow : Window, ICommon
{

    public MainWindow()
    {
        InitializeComponent();
        Program test = new Program();
        thisButton.Click += delegate(object sender, RoutedEventArgs e) { test.WhenPressed_1(this); };
    }

    public void SetValueInMain()
    {
        // Set Main values
    }

    public class Program
    {
        public string Word { get; set; }
        public void WhenPressed_1(ICommon mainWind)
        {
            mainWind.SetValueInMain();
        }
    }
}

public interface ICommon
{
    void SetValueInMain();
}

这篇关于尝试将MainWindow继承到子类中,但得到系统stackoverflow的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-26 23:21