Search code examples
c#wpfthisextend

C# WPF application: What is "this"?


I have been playing a lot with WPF applications in C# and there are a lot of things that are not really clear to me, I have been trying to look it up and play around with it to figure it out but without much success since english is my second tongue and I am still not that good with terminology nor with programming...

1: What is "this" in the main class? When I create the new WPF application in XAML I get window and a grid. However, I dislike XAML greatly and like to write code for all the elements and objects that I need so I delete that first grid, make a class, define my grid and to add it I have to write something like

   this.AddChild(myGrid);

which is fine, but if I want to use "this" from my main class in other classes, it becomes a bit complicated to me. So, which UIElement or Object is "this"? How do I define it so it can be used in methods? "this", I suppose refers to the Window that is created at beginning, but what UIElement or Object is that Window?

2: Extended classes?? I have been watching a lot of java tutorials lately, simply to learn more about programming. There, to use the objects from other class you can simply write:

   public class class1 extends class2{}

and everything is perfect, I have found out that I can mimic that same thing in C# WPF unless it's the main class, since main class extends :Window and I guess since it's defined as partial class... Is there a way to "extend" multiple classes or go around this?

Any help on clearing this up would be great :)


Solution

  • For the part about 'this' and its identity, the Window sits in a hierarchy of classes and can assume the identity of any of its ancestors. For example...

        public MainWindow()
        {
            InitializeComponent();
            var contentControl = this as ContentControl;
            var control = this as Control;
            var frameworkElement = this as FrameworkElement;
            var uiElement = this as UIElement;
            var dependencyObject = this as DependencyObject;
            var dispatcher = this as DispatcherObject;
        }
    

    ...all of the assignments in this snippet are legal. Also, there are more exotic assignments such as

    var x = this as IInputElement;
    

    The key here is to examine the framework and the various assignments available to each class. As others have pointed out, offline reading is essential to a quick learning curve.

    The etymology of 'this' as a keyword in an object oriented context extends back to the late 1970's when it first appeared in an early specification for C++.

    Finally, Xaml is one of the most attractive features of WPF for lots of reasons, and if Xaml isn't compatible with your approach, you MIGHT be better off in WinForms or Swing or similar tightly bound framework.