gpt4 book ai didi

wpf - 将一个大 XAML 拆分为多个 Sub-XAML 文件

转载 作者:行者123 更新时间:2023-12-03 04:58:33 28 4
gpt4 key购买 nike

在我的基于 WPF4 桌面的应用程序中,有一个带有侧边栏菜单的大块,该菜单在每个窗口中重复,并且需要大约 70 行 XAML。为了提高代码重用,我想将XAML文件拆分为两个文件:

  1. 包含侧边栏菜单代码的 XAML 文件(约 70 行)
  2. 基础 XAML 文件,其中包含带有侧边栏菜单代码的 XAML 文件的“包含/引用”

据我了解,有两种方法可以解决我的问题:

  1. 使用ResourceDictionary
  2. 使用UserControl/CustomControl

我的问题:

  1. ResourceDictionaryUserControl 之间有什么区别?您能否举例说明我必须使用 UserControl 以及 ResourceDictionary 的情况?

  2. 您能否提供一个完整的代码示例,说明如何将一个 XAML 文件的内容包含/导入到另一个 XAML 文件中?

附注以下是我想要导出到单独的 XAML 文件的代码示例:

<Border Style = "{StaticResource Body_SideBarMenu_Border_Settings}">
<StackPanel Style = "{StaticResource Body_SideBarMenu}">
<TextBlock Style = "{StaticResource Body_SideBarMenu_Title}"
Text = "{x:Static res:Resources.WinApp_SideBarMenu_Title}" />
<TextBlock x:Name = "SideBar_WinReports"
Style = "{StaticResource Body_SideBarMenu_Item}"
Text = "{x:Static res:Resources.DashListMarker}">
<Hyperlink KeyboardNavigation.TabIndex = "12"
Style = "{StaticResource Body_SideBarMenu_Item_Hyperlink}"
Click = "Call_WinReports_Click">
<TextBlock Text = "{x:Static res:Resources.WinApp_ModuleName_Reports}" />
</Hyperlink>
</TextBlock>
</StackPanel>
</Border>

最佳答案

ResourceDictionary 只是样式/模板等的容器。因此,您确实可以选择使用样式(并通过 ResourceDictionary 引用它)或 UserControl。

为了区分两者,问自己一个问题:您是否正在实现某些现有控件的另一种外观,或者您正在实现一些真正新的东西,这不仅仅是一个 ListView(或一个 Border,或一个 ComboBox) ETC。)?在前一种情况下,使用样式;在后者中,创建一个新的 UserControl。

特别针对您的情况,我会选择 UserControl。

<小时/>

代码示例(虽然不完整)

(请注意,可以使用VS的“添加新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,
}
}

现在,您可以像这样使用该控件:

<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>

关于wpf - 将一个大 XAML 拆分为多个 Sub-XAML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4977872/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com