使用英语阅读

通过


Control.Background 属性

定义

获取或设置一个用于描述控件背景的画笔。

[System.ComponentModel.Bindable(true)]
public System.Windows.Media.Brush Background { get; set; }

属性值

用于填充控件背景的画笔。 默认值为 Transparent

属性

示例

以下示例演示如何设置 控件的背景属性。

<Button Name="btn" Background="Red" 
        Click="ChangeBackground">
  Background
</Button>
void ChangeBackground(object sender, RoutedEventArgs e)
{
    if (btn.Background == Brushes.Red)
    {
        btn.Background = new LinearGradientBrush(Colors.LightBlue, Colors.SlateBlue, 90);
        btn.Content = "Control background changes from red to a blue gradient.";
    }
    else
    {
        btn.Background = Brushes.Red;
        btn.Content = "Background";
    }
}

以下示例演示一个模板,该模板允许触发器在按下按钮时更改按钮的背景。

<Button FontSize="16" FontWeight="Bold">Click the Background
  <Button.Template>
    <ControlTemplate TargetType="{x:Type Button}">
      <Border Background="{TemplateBinding Background}">
         <ContentPresenter/>
      </Border>
    </ControlTemplate>
  </Button.Template>

  <Button.Style>
    <Style TargetType="{x:Type Button}">
      <Setter Property="Background" Value="Blue"/>
      <Style.Triggers>
        <Trigger Property="IsPressed" Value="true">
          <Setter Property="Background" Value="Red"/>
        </Trigger>
      </Style.Triggers>
    </Style>
  </Button.Style>
</Button>

注解

属性 Background 仅适用于控件的静态状态。 控件的默认样式指定控件状态更改时其外观。 例如,如果在 上Button设置 Background 属性,则仅当按钮未按下或禁用时才具有该值。 如果要创建具有更高级背景自定义的控件,则必须定义控件的样式。

此属性仅影响其模板使用 属性作为参数的 Background 控件。 在其他控件上,此属性没有影响。

依赖项属性信息

标识符字段 BackgroundProperty
元数据属性设置为 true AffectsRender, SubPropertiesDoNotAffectRender

适用于

产品 版本
.NET Framework 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9