Home > Back-end >  Why is the root element of MainWindow Window instead of MainWindow?
Why is the root element of MainWindow Window instead of MainWindow?

Time:12-01

I notice that the root element in any XAML file (in WPF) seems to be one of:

  • Window
  • Page
  • UserControl
  • ResourceDictionary
  • Application

I tried to change the root element to local:MainWindow, but then the project cannot compile, saying the base class of a partial class should be the same. Then I guess the root element is the base class of the actual class? What is the reason for it? Since the root element cannot be changed to the actual class, I cannot access the dependency properties written in MainWindow.xaml.cs. How can those DPs be referenced in XAML?

Besides, I also notice that some third-party themes also provide special window classes, and in that case, the root element is often changed. How is this being achieved? E.g. GlowWindow XAML markup.

Try it yourself and create a new window by specifying your MainWindow as root element. It is exactly the same scenario.

CodePudding user response:

I will supplement the answer from @thatguy.

In WPF, it is customary to separate the logic part of the control (which is written in Sharpe) from the visual part (which is written in XAML in the theme template).

For your example, creating a template is redundant. But it could be done like this:

    public class MainWindowBase : Window
    {
        public int SomeProperty
        {
            get { return (int)GetValue(SomePropertyProperty); }
            set { SetValue(SomePropertyProperty, value); }
        }

        public static readonly DependencyProperty SomePropertyProperty =
            DependencyProperty.Register("SomeProperty", typeof(int), typeof(MainWindowBase), new PropertyMetadata(0));
    }

    public partial class MainWindow : MainWindowBase
    {
        public MainWindow()
        {
            InitializeComponent();
<local:MainWindowBase x:Class="****.MainWindow"
  • Related