Alex Alex - 3 months ago 18
C# Question

Cannot access class from another class c#

I'm trying to access public partial class ChooseExercises : Window from public partial class YourProgress : Window, but it throws an exception:

System.InvalidCastException: 'Unable to cast object of type 'GymCheckList.YourProgress' to type 'GymCheckList.ChooseExercises'.'


The way I'm trying to access it is:

namespace GymCheckList
{
/// <summary>
/// Interaction logic for YourProgress.xaml
/// </summary>
public partial class YourProgress : Window
{
public YourProgress()
{
InitializeComponent();
}

private void TabThursday_Loaded(object sender, RoutedEventArgs e)
{
ChooseExercises ce = (ChooseExercises)Application.Current.MainWindow;
var lol = ce;
}


If I use ChooseExerises ce = new ChooseExercises(); it gives me empty ce incstance. What may cause the exception?
Thanks!

Edit

In ChooseExeprises class I used similar code to access the MainWindow class and it works fine:

namespace GymCheckList
{
/// <summary>
/// Interaction logic for ChooseExercises.xaml
/// </summary>
public partial class ChooseExercises : Window
{
public ChooseExercises()
{
InitializeComponent();
}
private List<string> data = new List<string>();
public void ComboBox_Loaded(object sender, RoutedEventArgs e)
{
MainWindow kek = (MainWindow)Application.Current.MainWindow;

mm8 mm8
Answer Source

Obviously your main window is a YourProgress but you could try to get a reference to the ChooseExercises window using the Application.Current.Windows collection:

private void TabThursday_Loaded(object sender, RoutedEventArgs e)
{
    ChooseExercises ce = Application.Current.Windows.OfType<ChooseExercises>().FirstOrDefault();
    ...
}