Answer the question
In order to leave comments, you need to log in
How to access the main window from another class in WPF?
I am writing a desktop app.
There is a MainWindow.xaml.cs class. This is the main window of the application
. I have a code that, on pressing a hot key, the window is toggled to fullscreen.
I don't want to write a lot of code in one MainWindow.xaml.cs file. I
need to break the code into classes
. How can I get window parameters in another class so that they can be manipulated?
For example, create a class HotKeys.cs and write code there that will be responsible only for the hot keys of the window
Code for the hot key:
this.ResizeMode = ResizeMode.NoResize;
this.WindowStyle = WindowStyle.None;
this.WindowState = WindowState.Maximized;
this.PreviewKeyDown +=
(s, e) =>
{
if (((Keyboard.Modifiers & ModifierKeys.Alt) == ModifierKeys.Alt) && Keyboard.IsKeyDown(Key.Enter))
{
if (this.WindowStyle != WindowStyle.SingleBorderWindow)
{
this.ResizeMode = ResizeMode.CanResize;
this.WindowStyle = WindowStyle.SingleBorderWindow;
this.WindowState = WindowState.Normal;
e.Handled = true;
}
else
{
this.ResizeMode = ResizeMode.NoResize;
this.WindowStyle = WindowStyle.None;
this.WindowState = WindowState.Maximized;
e.Handled = true;
}
}
};
namespace Toolkits
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
}
Answer the question
In order to leave comments, you need to log in
Passing this to the constructor of the new class.
class HotKeys
{
private MainWindow window;
//Конструктор
public HotKeys(MainWIndow _window)
{
window = _window;
}
}
namespace Toolkits
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
HotKeys hk = new HotKeys(this);
}
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question