【问题标题】:ItemControl background colorItemsControl 背景颜色
【发布时间】:2016-12-03 17:55:19
【问题描述】:

在一个全新的通用 Windows 平台应用程序中,我正在尝试设置 ItemsControl 的背景。但它似乎没有做任何事情。我对 VS 模板所做的唯一更改是在 MainPage.xaml 中,现在看起来像这样:

<Page
    x:Class="UWPPlayground.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:UWPPlayground"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" x:Name="Hello">
  <Grid Background="Blue">
    <Grid.ColumnDefinitions>
      <ColumnDefinition Width="*">

      </ColumnDefinition>
      <ColumnDefinition Width="*">

      </ColumnDefinition>
    </Grid.ColumnDefinitions>
    <ItemsControl Grid.Row="0" Grid.Column="0" Width="60" Height="30" Foreground="Wheat" Background="White">
      <TextBlock Text="Hello World!"></TextBlock>
      <TextBlock Text="Can you see this?"></TextBlock>
    </ItemsControl>
    <Grid Grid.Row="0" Grid.Column="1" Background="Purple"></Grid>
    </Grid>
</Page>

结果如下所示。 ItemsControl 的 Foreground 属性似乎工作得很好,因为 TextBlocks 有小麦色的文本。由于控件的尺寸较小,文本被截断,正如预期的那样。然而,背景是不可见的。我错过了什么?

【问题讨论】:

    标签: xaml background uwp itemscontrol


    【解决方案1】:

    ItemsControl 继承自 Control,它在基类级别定义了许多视觉属性,这些属性不一定直接影响控件的外观。这些属性通常通过 ControlTemplate 中的 TemplateBindings 引用,然后产生所需的外观。模板是否使用这些属性决定了它们是否有任何用处。

    您会注意到,更改 UserControl 的背景也无济于事(出于上述相同的原因)。

    像 Grid、Rectangle、Border(等)这样的非控件类确实支持开箱即用的这些属性,因为这些元素通常用于控件模板中以产生特定的外观。

    ItemsControl 派生类(如 ListView)支持背景属性的原因是其模板中的某些根级元素引用了背景属性(通过 TemplateBinding)。 ItemsControl 本身没有模板。

    我认为 Foreground 属性起作用的原因是它会从父级继承其值。 (一些依赖属性可以像这样继承它们的值)。

    为您的 ItemsControl 设置背景的最简单方法是将其包装在边框(或网格,they're essentially the same now)中,然后在 上设置背景画笔。

    我不建议您对示例执行以下操作,但如果您希望 Background 属性正常工作,则需要执行以下操作:

    <ItemsControl Background="Red">
        <ItemsControl.Template>
            <ControlTemplate TargetType="ItemsControl">
                <Grid Background="{TemplateBinding Background}">
                    <ItemsPresenter/>
                </Grid>
            </ControlTemplate>
        </ItemsControl.Template>
    </ItemsControl>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-04
      • 1970-01-01
      • 2016-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-30
      相关资源
      最近更新 更多