Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do WPF application require the use of XAML?

I am wanting to learn C# and it seems everyone is switching from using WinForms to using WPF. WPF applications seems so much more complicated to me because of the use of the .XAML files that are used to building the Forms.

I am just asking before I get really involved, is the XAML files the only way to build WPF applications? Is there an easier method? I know I could just learn to use the WinForms which seems a lot easier since you basically have a Form object that you work with code but like I mentioned I think it would be best to build WPF apps

like image 782
JasonDavis Avatar asked Jan 07 '12 00:01

JasonDavis


1 Answers

XAML does make things a lot easier if you know how to use it because it is more readable and declarative, but you can do (pretty much) anything in C# code as well if you like.

e.g.

<Border BorderBrush="Red">
    <TextBlock Text="Lorem Ipsum"/>
</Border>

vs.

var border = new Border();
border.BorderBrush = Brushes.Red;
var textBlock = new TextBlock();
textBlock.Text = "Lorem Ipsum";
// The following step is implicit in XAML via the structure
border.Child = textBlock;

Though this can be written more concisely and hierarchically:

new Border
{
    BorderBrush = Brushes.Red,
    Child = new TextBlock
    {
        Text = "Lorem Ipsum"
    }
};

Generally i would always recommend using XAML, reasons include:

  • The parser optimizes the tree construction according to WPF's layout system.
  • Creating DataTemplates in code is not supported. The construction using FrameworkElementFactories has been deprecated in favour of using the XamlParser (and i definitely do not recommend juggling XAML strings in code).
  • Separation between UI and code.
like image 110
H.B. Avatar answered Oct 02 '22 08:10

H.B.