c# - 如何在 XAML 中重复编程行?
问题描述
...“编程线”一词是指代码的一部分。
我目前正在使用 c# 和 XAML 创建一个 UI。但是 XAML 代码越来越长,所以我意识到如果我能以某种方式在代码内部设置或单独存储可重复的代码部分并在每次需要时使用它们,那么整个 XAML 代码会更短更清晰。
例如,假设我有一个特定的标签,我想在代码的几个点重复:
<Label Name="myLabel" Content="something">
</Label>
我怎么可能在我的 XAML 代码中应用和重复该标签?
解决方案
有一个关于如何在不同视图/窗口之间共享 XAML 代码的快速示例。创建一个ResourceDictionary
,定义共享的属性/样式/控件模板,像这样
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style TargetType="{x:Type Label}">
<Setter Property="Foreground" Value="Black" />
<Setter Property="FontFamily" Value="Segoe UI" />
</Style>
<Style TargetType="{x:Type Button}">
<Setter Property="Foreground" Value="Black" />
<Setter Property="FontFamily" Value="Segoe UI" />
</Style>
<Style TargetType="{x:Type TextBox}">
<Setter Property="Foreground" Value="Black" />
<Setter Property="FontFamily" Value="Segoe UI" />
</Style>
<Style TargetType="{x:Type ScrollBar}">
<Setter Property="Foreground" Value="Black" />
<Setter Property="FontFamily" Value="Segoe UI" />
</Style>
<Style TargetType="Label" x:Key="TitleStyle" BasedOn="{StaticResource {x:Type Label}}">
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="HorizontalAlignment" Value="Stretch" />
<Setter Property="VerticalAlignment" Value="Stretch"/>
<Setter Property="FontSize" Value="16" />
</Style>
</ResourceDictionary>
您可以将此字典添加到 App/WindowMergedDictionaries
以使用它们,例如
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Styles.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
请注意,这只是一个简单的例子来简要解释这个想法。您还可以查看Style.TargetType
文档以查看样式之间TargetType
和x:Key
样式中的解释
推荐阅读
- logstash - 如何使用 input-jdbc-plugin 修复 logstash 锁定错误?
- netbeans - 如何为 JTable 设置列标题?
- angular - 由于依赖关系,我在运行 Angular 应用程序时遇到问题?
- python-3.x - ODOO 12 menuitem 不出现
- python - 从 html 表单中获取数据并用烧瓶发回
- php - 当两个值的值不同时如何从数组中删除数组值
- java - 如何在Java中返回两个以上的地图对象
- javascript - 在 Safari - Canvas - 右键单击将图像另存为.. 未显示在上下文菜单中
- sql - 从最大值为 Amount 的表中选择日期和 ID
- java - 如何使用方法引用作为未来的回调?