Wpf get value to Form1 from mainWindow

Blader 156 Reputation points
2020-10-10T08:56:55.597+00:00

I have the MainWindow and Form1. I want to get the value from MainWindow to Form1. When i click on the button in Form1 the result is 0. Where do i do a mistake? Would you help me please?

<Window x:Class="WpfNewForm.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfNewForm"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Button Content="Button1" HorizontalAlignment="Left" Margin="233,116,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>
<Button Content="Button2" HorizontalAlignment="Left" Margin="233,141,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click_1"/>
</Grid>
</Window>

namespace WpfNewForm
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public int indexMax;
public int[] indexy = new int[1000];
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
for (int i = 1; i < 100; i++)
{
indexy[i] = i;
indexMax = i;
}
MessageBox.Show(indexMax.ToString());
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
Form1 form1 = new Form1();
form1.Show();
}
}
}

namespace WpfNewForm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
MainWindow mainWindow = new MainWindow();
MessageBox.Show(mainWindow.indexMax.ToString());
}
}
}

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,691 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 113.7K Reputation points
    2020-10-10T10:39:46.473+00:00

    Try something like this:

    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
       Form1 form1 = new Form1();
       form1.mainWindow = this;
       form1.Show();
    }
    . . .
    public partial class Form1 : Form
    {
       public MainWindow mainWindow;
    
       public Form1()
       {
          InitializeComponent();
       }
       private void button1_Click(object sender, EventArgs e)
       {
          MessageBox.Show(mainWindow.indexMax.ToString());
       }
    }
    
    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful