Search code examples
c#wpfcameramainwindow

How to access MainWindow's variables from second Window


Is there another way to access MainWindow's public variables than :

MainWindow mainWindow = Application.Current.Windows.OfType<MainWindow>().FirstOrDefault();
mainWindow.variable....

this work fine, but I'm creating a WPF application and integrating a USB Webcam to my project and using this code above to access MainWindow's variables. This causes some problems like program is still running when I close MainWindow and camera won't stop. Any suggestions?


Solution

  • This is an over simplified example for what i wrote in comments(you really should look at mvvm the example below is not mvvm).

    public class SelectedIndexData
    {
        public int SelectedIndex { get; set; }
    }
    
    public partial class MainWindow : Window
    {
    
        private readonly SelectedIndexData _selectedIndexData = new SelectedIndexData();
        public MainWindow()
        {
            InitializeComponent();
        }
    
    
        private void ComboBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            _selectedIndexData.SelectedIndex = ComboBox.SelectedIndex;
        }
    
    
        private void ShowChildWindow(object sender, RoutedEventArgs e)
        {
           new ChildWindow(_selectedIndexData).Show();
        }
    }
    
    public partial class ChildWindow : Window
    {
        private SelectedIndexData _selectedIndexData;
        public ChildWindow(SelectedIndexData selectedIndexData)
        {
            InitializeComponent();
            _selectedIndexData = selectedIndexData; // do whatever you want with your data here
    
        }
    }