首页 > 解决方案 > 如何在 XAML 中重复编程行?

问题描述

...“编程线”一词是指代码的一部分。

我目前正在使用 c# 和 XAML 创建一个 UI。但是 XAML 代码越来越长,所以我意识到如果我能以某种方式在代码内部设置或单独存储可重复的代码部分并在每次需要时使用它们,那么整个 XAML 代码会更短更清晰。

例如,假设我有一个特定的标签,我想在代码的几个点重复:

  <Label Name="myLabel" Content="something">
  </Label>

我怎么可能在我的 XAML 代码中应用和重复该标签?

标签: c#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文档以查看样式之间TargetTypex:Key样式中的解释


推荐阅读