Split one big XAML in number of Sub-XAML files

 ̄綄美尐妖づ 提交于 2019-11-30 06:17:36
Vlad

ResourceDictionary is just a container for your styles/templates etc. So you really have a choice between using a style (and referencing it through a ResourceDictionary) or a UserControl.

In order to differentiate between the two, ask yourself a question: are you implementing just another look for some existing control, or you are implementing something really new, which is more than just a ListView (or a Border, or a ComboBox etc.)? In the former case, use a style; in the latter, create a new UserControl.

Specifically for your case, I would go for a UserControl.


Code example (although not full)

(Please note that a template for the following code can be inserted with VS's "add new UserControl")

Xaml:

<UserControl x:Class="SomeNamespace.SidebarMenu"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <UserControl.Resources> <!-- you can define local styles here -->
        <Style x:Key="SidebarMenuTextblock" TargetType=TextBlock>
            ...
        </Style>
    </UserControl.Resources>

    <Border Background=...>
        <StackPanel>

            <TextBlock
                x:Name="Put_a_name_if_you_want_to_reference_this_item_in_code_behind"
                Style="{StaticResource SidebarMenuTextblock}"
                Text="{x:Static res:Resources.WinApp_SideBarMenu_Title}" />
            ...        </StackPanel>
    </Border>
</UserControl>

.cs:

using System;
using System.Windows;
using System.Windows.Controls;

namespace SomeNamespace
{
    public partial class SidebarMenu : UserControl
    {
        public NumericUpDown()
        {
            InitializeComponent();
        }
        ...
        // define here your properties etc,
    }
}

Now, you can use the control like that:

<Window
    x:Class="SomeOtherNamespace.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:controls="clr-namespace:SomeNamespace">

    <Grid>
        <controls:SidebarMenu PropertyIfYouDefinedOne="SomeValue"/>
        ...
    </Grid>

</Window>

If you can get your hands on Expression Studio, in Expression Blend, you can simply right click on any control and convert it to an user control. As easy as that.

User controls are good for splitting the XAML file. In essence, it is used to redefine the behavior of an existing control.

However, with User Controls, you can define whole WPF Layout Controls and convert them to an User Control, with the children content inside them. This is very helpful for a project spread across multiple developers, and can also be used to emulate the behavior of an MDI, which is kind of absent in WPF.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!