NET WPF内容控件ContentControls

2024-02-28  本文已影响0人  AC编程

一、WPF常用控件

WPF 的所有控件都是从System.Windows.Controls.Control 类中派生出来,其命名空间是System.Windows.Controls

WPF有两个类似的类继承树,一个与界面( UI )相关,如 UIElement 类;另一个与内容( Content )相关,如 ContentElement。ContentElement 支持文本方式,而 UIElement 则支持图形方式。Control 类中派生出来的控件,基本上可以分为4类:

内容控件(ContentControls)继承树:


内容控件

在Visual Studio中按F12可以查看到当前类的继承类。

二、内容控件(ContentControls)

内容控件是 WPF 控件中的一大类,ContentControl 直接从 Control 类中派生出来。内容控件包括:

内容控件

三、理解内容控件

继承了 ContentControl 的控件可以被称为内容控件,因为它们具有一个名为 Content 的属性,用于设置控件内的内容。通过设置 Content 属性,可以向这些控件中添加其他控件、文本、图像等内容,以实现更丰富和灵活的界面设计。

例如:可以在<Button> 控件中,加入图片<Image>、文字<TextBlock>两个控件,组成一个带图标和文字的按钮控件。

四、样例代码

4.1 ControlWindow.xaml
<Window x:Class="wpf_demo.ControlWindow"
        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:hc="https://handyorg.github.io/handycontrol"
        xmlns:local="clr-namespace:wpf_demo"
        mc:Ignorable="d"
        Title="内容控件" Height="400" Width="600">
    <Grid>
        <VirtualizingStackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
            <TextBlock Text="继承了ContentControl类的控件就是内容控件,在内容控件中可以再添加内容(控件)。" VerticalAlignment="Center" HorizontalAlignment="Center"></TextBlock>
            <TextBlock Text="这是一个带文字和图片的按钮" VerticalAlignment="Center" HorizontalAlignment="Center" Margin="0 20 0 0"></TextBlock>
            <Button Width="80" Height="30" Margin="0 20 0 0">
                <StackPanel Orientation="Horizontal">
                    <Image Width="20" Height="20" Source="/images/search.png"></Image>
                    <TextBlock Text="搜索" VerticalAlignment="Center" Margin="10 0 0 0"></TextBlock>
                </StackPanel>
            </Button>
        </VirtualizingStackPanel>
    </Grid>
</Window>
4.2 ControlWindow.xaml.cs

using System.Windows;

namespace wpf_demo
{
    public partial class ControlWindow : Window
    {
        public ControlWindow()
        {
            InitializeComponent();
        }
    }
}
4.3 效果
效果

参考:【C# .NET】WPF (五) 常用控件 之 内容控件 (ContentControls)

上一篇下一篇

猜你喜欢

热点阅读