我正在尝试使用XAML创建用户界面。但是,该文件很快变得非常庞大并且难以使用。将文件分成几个文件的最佳方法是什么。
我希望能够将一个元素(如ComboBox)的内容设置为在不同的xaml文件中定义的元素(但在同一个VS项目中)。
感谢
答案 0 :(得分:40)
您可以通过定义UserControls来拆分大型用户界面。
右键单击解决方案树,选择Add-> New Item ...然后选择User Control。你可以用正常的方式设计它。
然后,您可以使用命名空间声明在XAML中引用您的usercontrol。假设您想在窗口中包含UserControl。在下面的示例中,我将名为“Foo”的UserControl添加到名称空间“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 ... />
对于您的具体示例,您可以通过定义在您的用户控件中显示数据的DataTemplate,在组合框中使用您的usercontrol。
答案 1 :(得分:23)
您可以使用ResourceDictionary拆分XAML文件。 ResourceDictionary可用于合并其他文件:
<Page.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="myresourcedictionary.xaml"/>
<ResourceDictionary Source="myresourcedictionary2.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Page.Resources>
在ResourceDictionary中,您还可以声明可以在元素中使用的样式,以便主XAML文件变小。
获取较小的XAML文件的另一种可能性是定义您自己的控件,然后在主应用程序中使用。
答案 2 :(得分:1)
您还可以创建Page,而不是UserControl
。 Page
可以由Window
或Frame托管。let dateformatter = DateFormatter()
dateformatter.dateFormat = "HH:MM"
return dateformatter.string(from: (Date)_time)
。搜索Page vs UserControl的优缺点。这取决于您对导航的要求,以满足您的最佳需求。
答案 3 :(得分:-2)
使用样式和用户控件。将您的界面划分为较小的部分,并在另一个xaml文件中编码。 例如:
<Window>
<VeryBigControl>
<VeryBigControl.Style>
... <!--very long style-->
</VeryBigControl.Style>
.. <!--content of very big control-->
</VeryBigControl
</Window>
将其分为三个xaml文件:
Window.xaml - 这将是Window
VeryBigControl.xaml - 这将是UserControl
VeryBigControlStyle.xaml - 这将是资源字典
等等:)