Trying to inherit MainWindow into subclass but get

2019-08-20 16:22发布

I'm trying to send extra variables to a WPF Event handler.

I've tried using a delegate to send it to another function that holds the variable I need 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); };
    }       
}

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

I know this code is a huge mess and isn't the way it should be done but I haven't found a working solution anywhere for sending and changing a variable in a WPF event handler. IF there is another solution other than this far off method then it's welcomed if what I'm asking isn't possible then just say.

Thanks (Sorry for this wordy question)

1条回答
劳资没心,怎么记你
2楼-- · 2019-08-20 16:44

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();
}
查看更多
登录 后发表回答