WPF系列教程(十二):控件类——前景背景、字体

控件都包含背景画刷和前景画刷属性。
部分控件包含字体属性。
鼠标光标的设置。
示例项目源码

为控件设置背景与前景

下面这个窗体
在这里插入图片描述

<Window x:Class="Control.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Control"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800" Loaded="Window_Loaded">
    <Grid>
        <StackPanel Margin="5">
            <Button x:Name="button" Content="Button" Width="200"/>
        </StackPanel>

    </Grid>
</Window>

设置在加载窗体时,按钮背景色改为粉红:
添加窗体加载事件
在这里插入图片描述

 private void Window_Loaded(object sender, RoutedEventArgs e)
        {
    
    
            this.button.Background = new SolidColorBrush(Colors.Pink);  // 设置背景色
            this.button.Foreground = new SolidColorBrush(Colors.Red);  // 设置前景色
        }

运行起来
在这里插入图片描述
也可以用RGB去设置颜色

this.button.Background = new SolidColorBrush(Color.FromRgb(0,0,250));  // 设置背景色
this.button.Foreground = new SolidColorBrush(Color.FromRgb(255,0,0));  // 设置前景色

或者在XAML文件中设置

<Button x:Name="button" Content="Button" Width="200" Background="red" Foreground="AliceBlue"/>

Backgroud和Foreground都能够默认地创建SolidColorBrush画刷。

字体属性

FontFamily:字体种类(宋体、黑体)
FontSize:字体大小
FontStyle:字体样式,角度(斜体)
FontWeight:字体粗细
FontStretch:字体拉伸和压缩
wpf会从下面三种字体种依次读取,若有则不再读后续字体。

FontFamily="Times New Roman,Arial,Comic Sans MS"

我们加一个用于显示系统所有字体的ListBox:

private void Window_Loaded(object sender, RoutedEventArgs e)
        {
    
    
            foreach (FontFamily fontFamily in Fonts.SystemFontFamilies)
                this.listBox1.Items.Add(fontFamily);
        }

在这里插入图片描述
给字体装饰
设置属性
基线:TextDecorations=“Baseline”
中划线:TextDecorations=“Strikethrough”
下划线:TextDecorations=“Underline”
顶线:TextDecorations=“OverLine”

字体继承
在上级元素中设置字体属性,下级元素默认继承。
字体嵌入
使用系统没有安装的字体,在项目中添加现有项-字体.ttf文件,文件属性中生成操作修改为Resource,在需要设置字体属性的地方使用FontFamily = "./#字体"即可。

鼠标光标

用不同的光标表示程序处于不同的状态,通过设置Cursor属性实现。
在窗体加载时鼠标显示为等待(沙漏或者转圈)。
窗体加载事件中加入代码:

this.Cursor = Cursors.Wait;

在特定控件中可以直接设置Cursor属性切换不同的鼠标光标。

<Button x:Name="button" Content="Button" Width="200" Background="Pink" Foreground="Black" FontFamily="Times New Roman,Arial,Comic Sans MS" FontSize="21" Height="49" Cursor="Help"/>

鼠标移动至该按钮时,显示为带问号的帮助光标。

示例项目源码

おすすめ

転載: blog.csdn.net/qq_43511299/article/details/121495512