C
C#7mo ago
Mashmo

Inheriting a base window class in WPF

I have a couple of windows that use the same CloseWindow, MinimizeWindow, and WindowMouseDown functions that are implemented the same This feels kind of a bad practice, so I tried implementing a base function for window that has all 3 of those functions and inheriting it in all of those windows However it gave me a lot of problems in using the base Window functions (e.g. Show and Close) outside the class, and much more errors Does anybody know a better way to address this problem? This is the class I tried using as a base class:
C#
namespace Client
{
public abstract class TriviaClientWindow : Window
{
private void Window_MouseDown(object sender, MouseButtonEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
DragMove();
}
}
private void CloseWindow(object sender, RoutedEventArgs e)
{
((App)Application.Current).StopMusic();
Thread.Sleep(50);
Close();
}
private void MinimizeWindow(object sender, RoutedEventArgs e)
{
this.WindowState = WindowState.Minimized;
}
}
}
C#
namespace Client
{
public abstract class TriviaClientWindow : Window
{
private void Window_MouseDown(object sender, MouseButtonEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
DragMove();
}
}
private void CloseWindow(object sender, RoutedEventArgs e)
{
((App)Application.Current).StopMusic();
Thread.Sleep(50);
Close();
}
private void MinimizeWindow(object sender, RoutedEventArgs e)
{
this.WindowState = WindowState.Minimized;
}
}
}
6 Replies
SpReeD
SpReeD7mo ago
What kind of errors do you encounter?
Mashmo
MashmoOP7mo ago
There is a window that wont allow me to inherit the class since the .g.i.cs file inherits System.Windows.Window and i cant change that namespace Client {

C#
/// <summary>
/// MainMenu
/// </summary>
public partial class MainMenu : System.Windows.Window, System.Windows.Markup.IComponentConnector {
...
}
C#
/// <summary>
/// MainMenu
/// </summary>
public partial class MainMenu : System.Windows.Window, System.Windows.Markup.IComponentConnector {
...
}
SpReeD
SpReeD7mo ago
Have you changed the XAML accordingly?
Mashmo
MashmoOP7mo ago
How so?
SpReeD
SpReeD7mo ago
If your C# code inherits from anything other than Window you need to change it in XAML as well. The g.i.cs is auto-generated. I assume your C# class definition looks like
public partial class MainWindow : TriviaClientWindow
public partial class MainWindow : TriviaClientWindow
So your XAML need to look like this:
<cl:TriviaClientWindow x:Class="Views.MainWindow"
xmlns:cl="clr-namespace:Client"
...>
<cl:TriviaClientWindow x:Class="Views.MainWindow"
xmlns:cl="clr-namespace:Client"
...>
Mashmo
MashmoOP7mo ago
Got it, thanks
Want results from more Discord servers?
Add your server