What is the easiest way to break up large XAML files in my application?

后端 未结 3 2032
灰色年华
灰色年华 2021-02-08 12:57

I recently discovered that I could make use of user controls to reduce the size of my main application\'s .xaml file. I am new to WPF and realized that my app\'s XAML is getting

相关标签:
3条回答
  • 2021-02-08 13:32

    User controls are a very good way to isolate code out of the main window. In addition to decluttering, they also provide other advantages such as modularizing the code and providing a limited interface into that section of code, which helps improve maintainability and helps prevent spaghetti code.

    In addition to that, DataTemplates can also be useful. For example, suppose you have a bunch of fields that need to be entered in and all of those fields have labels. In that case, you can create a class with two properties, one for the label and one for the value of that field. You can then create a DataTemplate for that class that binds the label to a TextBlock and the value to a TextBox. If you want all of the labels to line up, you can create a Grid SharedSizeScope. After you do that, you can then create an ObservableCollection of that class, fill the collection with labels and values, and then set the ItemsSource of an ItemsControl to it. After you get the initial plumbing of this going, data entry forms can be generated way faster than they can in WinForms.

    0 讨论(0)
  • 2021-02-08 13:44

    You're correct that splitting things into seperate controls can help reduce the size of individual xaml files. The other way to reduce the size of the files is to make use of ResourceDictionaries. When you split your Styles, Templates, and Resources into seperate ResourceDictionaries it can greatly reduce the size of your window's and control's xaml files. Once stuff is split up, you can make use of the MergedDictionaries feature to access the styles and templates from wherever you need them. If a specific resource is used throughout multiple windows and controls, you can also merge it's ResourceDictionary into the App.xaml resources, thus allowing it to be used from any location in the solution.

    Personally, I like to keep each XAML file to around ~300 or less lines, after that point I see if there's a better way I should have it organized. Here's some additional info and tips on how to keep your Resources organized.

    0 讨论(0)
  • 2021-02-08 13:49

    Also for theming/styling avoid putting in styles at the control/individual level, rather have the theme.xaml handle the skinning directly, that way you don't have the bloat of styling information inside the Xaml.

    i.e. <MyControl Style="{StaticResource myControlStyle}"/> could be avoided by directly applying the styling on MyControl in the theme file, that way you only have <MyControl/> in the Window.xaml

    0 讨论(0)
提交回复
热议问题