Cannot access class from another class c# - 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;

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();
...
}

Related

Creating a "Team" in another window(TeamCreatorWindow) and save the object to be displayed in a "Listbox" in Main Window EDITED

namespace WpfApp1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
// Function for creating Team
public void AddToListBox(string MyTeam)
{
AddTeamBox.Items.Add(MyTeam);
}
private void AddTeam_Click(object sender, RoutedEventArgs e)
{
TeamCreatorWindow TeamCreatorPopup = new TeamCreatorWindow();
TeamCreatorPopup.Show();
}
}
}
this is the code for my "MainWindow"
namespace WpfApp1
{
/// <summary>
/// Interaction logic for TeamCreatorWindow.xaml
/// </summary>
public partial class TeamCreatorWindow : Window
{
public string NameTeam;
public string KeyPlayer;
public string Knep;
public TeamCreatorWindow()
{
InitializeComponent();
}
class CreatedTeam : TeamCreatorWindow
{
public CreatedTeam(string TeamName, string TeamKnep, string KeyPlayers)
{
TeamName = NameTeam;
TeamKnep = Knep;
KeyPlayers = KeyPlayer;
}
}
private void CancelTeamCreator_Click(object sender, RoutedEventArgs e)
{
Close();
}
private void CreateTeambutton_Click(object sender, RoutedEventArgs e)
{
CreatedTeam team = new CreatedTeam(NameTeam, Knep, KeyPlayer);
}
private void KeyPlayerTxtBox_KeyDown(object sender, KeyEventArgs e)
{
KeyPlayer = KeyPlayerTxtBox.Text;
}
private void TeamNameTxtBox_KeyDown(object sender, KeyEventArgs e)
{
NameTeam = TeamNameTxtBox.Text;
}
private void HemmaButton_Click(object sender, RoutedEventArgs e)
{
HemmaButton.IsChecked = true;
BortaButton.IsChecked = false;
HemmaButton.BorderBrush = Brushes.Green;
BortaButton.BorderBrush = Brushes.Gray;
Knep = HemmaBlock.Text;
}
private void BortaButton_Click(object sender, RoutedEventArgs e)
{
BortaButton.IsChecked = true;
HemmaButton.IsChecked = false;
HemmaButton.BorderBrush = Brushes.Gray;
BortaButton.BorderBrush = Brushes.Green;
Knep = BortaBlock.Text;
}
}
}
This is code for the "TeamCreatorWindow" here i am getting information for the teams from TextBoxes and storing the text into strings( TeamName, Knep and KeyPlayer) i have a CreateTeamButton, when the CreateTeamButton is clicked it should store the Object into The listBox from Mainwindow called "AddTeamBox". I have tried creating a public function in mainwindow called "AddToListBox" but i cant access it in my TeamCreatorWindow anyway. what is the right way to do this?

How to share data from one view to another?

I have some problems with simple variable sharing between different views.
I have first main view called MainPage.xaml and second called Page2.xaml.
I want to check which radiobutton on MainPage.xaml is checked and send a variable with that date to Page2.xaml.
MainPage:
namespace IDG
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public string choice;
public MainPage()
{
this.InitializeComponent();
}
private void bt_start_Click(object sender, RoutedEventArgs e)
{
if (rb_choice1.IsChecked == true)
{
choice = "choice1";
}
if (rb_quiz.IsChecked == true)
{
this.Frame.Navigate(typeof(Page2), choice);
}
}
}
}
And Page2:
namespace IDG
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class Page2 : Page
{
private string x;
public Page2()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
var param = e.Parameter as string;
x = param;
textBlock1.Text = x;
}
private void button_Click(object sender, RoutedEventArgs e)
{
this.Frame.Navigate(typeof(MainPage));
}
}
}
And I want this parameter to be stored in main class, how to do it?
On Page 2 in the OnNavigatedTo event retreive the value like this: var param = e.Parameter as string
EDIT
Assign the retreived parameter to the textblock in the OnNavigatedTo. At the time the page is constructed the value of x is "".
public sealed partial class Page2 : Page
{
private string x="";
public Page2()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
x = e.Parameter as string;
textBlock1.Text = x;
}
private void button_Click(object sender, RoutedEventArgs e)
{
this.Frame.Navigate(typeof(MainPage));
}
}
Recently, I'm working on WPF project but we use it with DevExpress library, and for your issue, it's very easy to be fixed with Messenger in DevExpress.
We just register the messenger where you want to receive the data,
public class Message {
//...
}
public class Recipient {
public Recipient() {
Messenger.Default.Register<string>(this, OnMessage1);
Messenger.Default.Register<Message>(this, OnMessage2);
}
void SendMessages() {
Messenger.Default.Send("test");
Messenger.Default.Send(new Message());
}
void OnMessage1(string message) {
//...
}
void OnMessage2(Message message) {
//...
}
}
And then you can send it from another view,
public class InheritedMessage : Message {
//...
}
public class Recipient {
public Recipient() {
//Inherited messages are not processed with this subscription
Messenger.Default.Register<Message>(
recipient: this,
action: OnMessage);
//Inherited messages are processed with this subscription
Messenger.Default.Register<Message>(
recipient: this,
receiveInheritedMessagesToo: true,
action: OnMessage);
}
void SendMessages() {
Messenger.Default.Send(new Message());
Messenger.Default.Send(new InheritedMessage());
}
void OnMessage(Message message) {
//...
}
}
With it, you can pass data between modules (or views, but recommend to use MVVM)
If you want to know more about DevExpress, please go through https://documentation.devexpress.com/#WPF/CustomDocument17474
Hope it could help you. :)

Event recognition C# WPF

I got an Problem with Events. I got a first Window which looks like this:
using System.Windows;
namespace EventsTests
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
/*Binding Event to MainWindow
dont work until you will help*/
MainWindow mw = new MainWindow();
mw.RaiseEvent += raiseEvent_EventHandler;
}
public void raiseEvent_EventHandler()
{
MessageBox.Show("MAINWINDOW Event Fired");
}
private void Button_Click(object sender, RoutedEventArgs e)
{
SecondPage sp = new SecondPage();
sp.Show();
}
}
}
Now the seconde Page donĀ“t do very much:
using System.Windows;
namespace EventsTests
{
/// <summary>
/// Interaction logic for SecondPage.xaml
/// </summary>
public partial class SecondPage : Window
{
SecondPageViewModel spvm = new SecondPageViewModel();
public SecondPage()
{
this.DataContext = spvm;
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
spvm.raiseEventActivate();
}
}
}
And at last I have the SecondPageViewModel:
namespace EventsTests
{
public delegate void raiseEventEventHandler();
class SecondPageViewModel
{
public event raiseEventEventHandler raiseEvent;
public void raiseEventActivate()
{
if(raiseEvent != null)
{
raiseEvent();
}
}
}
}
Now I want, when I click the button on the second page, the Event is fired an the MainWindow recognise the event.
With this code i get the Error:
Error 1 Cannot assign to 'RaiseEvent' because it is a 'method group'
Can someone help me? Or give me an example?
Thanks for every hint ;)
RaiseEvent is not your event, it's a method of the Window.
I think you want to do this:
SecondPage sp = new SecondPage();
sp.raiseEvent += raiseEvent_EventHandler;
sp.Show();
That is, register an event handler with the second page event.
Though I wouldn't advocate event handlers for this. While I don't know what you are trying to achieve I'd rather do something like pass a ViewModel object to the SecondPage and the main window can respond to state changes on that ViewModel.
In WPF, I always aim for zero code behind.
In response to discussion, how one VM could have reference to another. First pass the VM in:
SecondPageViewModel spvm;
public SecondPage(SecondPageViewModel model)
{
spvm = model;
this.DataContext = spvm;
InitializeComponent();
}
Then the SecondpageVM takes a MainVM as a paramter in the constuctor:
SecondPage sp = new SecondPage(new SecondPageViewModel(mainVM));
Updates to the main model are done within the SecondPageViewModel. The second page itself has no references to it.
ThirdPage tp = new ThirdPage(new ThirdPageViewModel(spvm))
Third page VM can access main page VM via property on second page vm: spvm.MainVm
In MainWindow you're trying to subscribe to a Window method, instead of your raiseEvent. And certainly you don't need to instantiate another MainWindow...
Your MainWindow code should be something like this:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public void raiseEventFromSecondPage_EventHandler()
{
MessageBox.Show("MAINWINDOW Event Fired");
}
private void Button_Click(object sender, RoutedEventArgs e)
{
SecondPage sp = new SecondPage();
sp.raiseEventFromSecondPage += raiseEventFromSecondPage_EventHandler();
sp.Show();
}
}
You then need that SecondPage exposes the raiseEvent. This will be a different event from the one in its ViewModel, but you'll chain both.
public partial class SecondPage : Window
{
SecondPageViewModel spvm = new SecondPageViewModel();
public event raiseEventEventHandler raiseEventFromSecondPage;
public SecondPage()
{
this.DataContext = spvm;
spvm.raiseEvent += raiseEvent_EventHandler;
InitializeComponent();
}
public void raiseEvent_EventHandler()
{
if (raiseEventFromSecondPage != null)
raiseEventFromSecondPage();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
spvm.raiseEventActivate();
}
}

Execution of code after user clicks on close icon [duplicate]

I am not familiar with using event handlers, and I was wondering if anyone had or could direct me to some code that shows how to use an event handler that will execute code on the Close/Closed event?
I know this can be done because of this answered question:
Run code on WPF form close
But I need some direction.
Thank you =)
It's just this XAML
<Window ... Closing="Window_Closing" Closed="Window_Closed">
...
</Window>
and code for both the Closing and Closed events
private void Window_Closing(object sender, CancelEventArgs e)
{
...
}
private void Window_Closed(object sender, EventArgs e)
{
....
}
If you want to do it all from code behind put this in your windows .cs file
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.Closed += new EventHandler(MainWindow_Closed);
}
void MainWindow_Closed(object sender, EventArgs e)
{
//Put your close code here
}
}
}
If you want to do part in xaml and part in code behind do this in xaml
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" Closed="MainWindow_Closed">
<Grid>
</Grid>
</Window>
and this in .cs
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
void MainWindow_Closed(object sender, EventArgs e)
{
//Put your close code here
}
}
}
The above to examples you can apply to any form in a xaml app. You can have multiple forms. If you want to apply code for the entire application exit process modify your app.xaml.cs file to this
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
protected override void OnExit(ExitEventArgs e)
{
try
{
//Put your special code here
}
finally
{
base.OnExit(e);
}
}
}
}
You can override the OnExit function in App.Xaml.cs like this:
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
protected override void OnExit(ExitEventArgs e)
{
//do your things
base.OnExit(e);
}
}
If you are using C# on Microsoft Visual Studio, the following worked for me.
In your Window.cs file
using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace Name_Space
{
public partial class Window : Form
{
public Window()
{
InitializeComponent();
//...
}
private void Window_Load(object sender, EventArgs e)
{
//...
}
private void Window_Closed(object sender, EventArgs e)
{
// Your code goes here...!
}
}
}
In your Window.Designer.cs file add this line to the following method
...
private void InitializeComponent()
{
...
//
// Window
//
...
this.Closed += new System.EventHandler(this.Window_Closed); // <-- add this line
}
...

C# WPF page switching

I want to accomplish something like they have in Modern UI for WPF. I have MainWindow : NavigationWindow, which source is page /main.xaml and my code in it looks like this:
public partial class main : Page
{
public main()
{
InitializeComponent();
}
private void settings_Click(object sender, RoutedEventArgs e)
{
settings settingsmenu = new settings();
this.NavigationService.Navigate(settingsmenu);
}
}
The problem is, that when i switch pages, annoying sound appears. I think it's named "navigation start". Can i prevent it from playing ? Or is there another way to switch pages, that doesn't play it ? Thanks in advance.
(sorry if this question is dumb, but I'm new to WPF)
Here is a small workaround. Original sources I found here:
http://social.msdn.microsoft.com/Forums/vstudio/en-us/843677f4-8f0b-46cb-986c-92e8042d0707/stupid-problem-with-webbrowser-control
using System.Windows;
using System.Windows.Controls;
using Microsoft.Win32;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for Page1.xaml
/// </summary>
public partial class Page1 : Page
{
private RegistryKey regKeyCurrentUser;
private RegistryKey regSubKeyCurrent;
public Page1()
{
InitializeComponent();
}
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
var page2 = new Page2();
this.NavigationService.Navigate(page2);
}
private void Page1_OnLoaded(object sender, RoutedEventArgs e)
{
regKeyCurrentUser = Registry.CurrentUser;
regSubKeyCurrent = regKeyCurrentUser.OpenSubKey(#"AppEvents\Schemes\Apps\Explorer\Navigating\.Current", true);
regSubKeyCurrent.SetValue("", "");
}
private void Page_Unloaded(object sender, RoutedEventArgs e)
{
var regSubKeyDefault = regKeyCurrentUser.OpenSubKey(#"AppEvents\Schemes\Apps\Explorer\Navigating\.Default");
regSubKeyCurrent.SetValue("", regSubKeyDefault.GetValue("",""));
}
}
}

Categories

Resources