XAML or C# code-behind

后端 未结 20 1908
盖世英雄少女心
盖世英雄少女心 2020-12-13 02:03

I don\'t like to use XAML. I prefer to code everything in C#, but I think that I am doing things wrong.

In which cases it is better to use XAML and when do you use C

20条回答
  •  抹茶落季
    2020-12-13 02:41

    Basically, XAML is meant for expressing visual-design, C# is meant for expressing logic.

    Any visual design should be done in XAML, any logic should be implemented in C#.

    - This enables giving the visual design to a designer to play on without worrying about changes to the logic and even replacing the entire visual design at run time using loose-XAML.

    - This also means you could replace either the logic or the visual-design without "breaking" either.

    - The connection between the two should be done with data bindings and with command bindings.

    The practice I use is:

    1. Define the model (the business data object model) in separate C# code.

    2. Define the constant parts of the view (the constant parts of the graphical user interface, e.g. the windows, menus, ...) in XAML (preferably use Blend and not VS for this).
    * Do not define styling (colors, fonts, ...) here.
    * Do not write event handlers for buttons (in most cases) in code-behind-the-XAML, use command-bindings instead.

    3. Define how the model is presented within the view (the GUI for viewing/editing the data objects) using XAML "ResourceDictionary"s located in separate files.

    - Write using blend then add bindings to XAML using VS (Jetbrains' Resharper add-on for VS will help with binding expressions).

    - If the object types are not known during design-time you can use "loose-XAML" and place the XAML in a folder which can have files added to / edited within without recompiling.

    4. Create a connection between the model and the view (a controller/view-model) in C# which:
    * Creates views as necessary (for dynamics objects)
    * Data-binds the view to the model (sets view's DataSource as the relevant object within the model)
    * Implements the commands
    * Command-binds the view to the command implementations within itself

    5. In Application.xaml delete the StartupUri="MainWindow.xaml" and add Startup="ApplicaitonStartUp" instead.
    Within the ApplicationStartUp() event handler:
    * Load any loose-XAMLs you have
    * Create the controller
    * Create the main window
    * Create the model
    * Connect controller to model and main window
    * Show main window
    * (Save model, controller and main window into private fields here to make sure they are all kept alive)

    6. Add styling (colors, fonts) to a separate XAML file under a ResourceDictionary (using blend for this or purchase a ready made XAML theme/skin file).

提交回复
热议问题