Splitting WPF interface across multiple Xaml files

后端 未结 4 1293
南旧
南旧 2020-12-25 09:51

I am trying to create a user interface using XAML. However, the file is quickly becoming very large and difficult to work with. What is the best way for splitting it across

相关标签:
4条回答
  • 2020-12-25 10:12

    Use styles and user controls. Divide your interface on smaller parts and code them in another xaml files. Example:

    <Window>
    <VeryBigControl>
    <VeryBigControl.Style>
    ... <!--very long style-->
    </VeryBigControl.Style>
    .. <!--content of very big control-->
    </VeryBigControl
    </Window>

    divide it into three xaml files:
    Window.xaml - this will be Window
    VeryBigControl.xaml - this will be UserControl
    VeryBigControlStyle.xaml - this will be resource dictionary
    and so on :)

    0 讨论(0)
  • 2020-12-25 10:17

    You can split a large user interface by defining UserControls.

    Right-click on the solution tree, choose Add->New Item... then User Control. You can design this in the normal way.

    You can then reference your usercontrol in XAML using a namespace declaration. Let's say you want to include your UserControl in a Window. In the following example I've added a UserControl named "Foo" to the namespace "YourCompany.Controls":

    <Window x:Class="YourCompany.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:Controls="clr-namespace:YourCompany.Controls">
    
      <Controls:Foo ... />
    

    For your specific example, you would make use of your usercontrol in a combobox by defining a DataTemplate that displayed the data within your usercontrol.

    0 讨论(0)
  • 2020-12-25 10:33

    You can also create a Page, instead of a UserControl. A Page can be hosted by the Window or by a Frame. Search for the pros and cons of a Page vs UserControl. It depends a bit on your requirements with respect to navigation which will suit your needs best.

    Here is an example of using a Page in a Frame.

    0 讨论(0)
  • 2020-12-25 10:34

    You can split up XAML files by using a ResourceDictionary. The ResourceDictionary can be used to merge other files:

    <Page.Resources>
      <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
          <ResourceDictionary Source="myresourcedictionary.xaml"/>
          <ResourceDictionary Source="myresourcedictionary2.xaml"/>
        </ResourceDictionary.MergedDictionaries>
      </ResourceDictionary>
    </Page.Resources>
    

    In the ResourceDictionary, you can also declare Styles that you can use at your elements, such that the main XAML file gets smaller.

    Another possibility to get a smaller XAML file is to define your own controls that you then use in your main app.

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