WPF (1) WPF basic controls and layout

​ WPF (Windows Presentation Foundation) is a Windows-based user interface framework launched by Microsoft. It is translated into "Windows Presentation Foundation" in Chinese and is part of .NET Framework 3.0. WPF is similar to the WinForm technical framework, but compared to WinForm, WPF expands most of the basic functions more powerfully, and introduces the XAML markup language, which truly realizes the front-end separation of developers and designers, and derives A set of MVVM development framework. Some references are as follows:

1. Introduction to basic controls

1. WPF UI element inheritance relationship


insert image description here

2. Basic controls

2.1 TextBlock

Simply put, TextBlock is a text block used to present text content. TextBlock can contain its Text property or Inline flow content elements in inline format (similar to HTML language. These small control-like structures are inherited from the Inline class and can be rendered inline as part of the text, such as bold Bold , italic Italic, Underline Underline, etc.).

- Foreground : 获取或设置要应用到 TextBlock 的文本内容的 Brush(文本颜色刷)。
- Background : 获取或设置要用于填充内容区域背景的 Brush(文本块背景颜色刷)。
- TextTrimming : 获取或设置在内容超出内容区域时要采用的文本剪裁行为(CharacterEllipsis字符边界裁剪、None不裁剪、WordEllipsis单词边界裁剪)。
- TextWrapping : 获取或设置 TextBlock 对文本进行换行的方式(Wrap自动换行、NoWrap不换行)。
- Text : 获取或设置 TextBlock 的文本内容,等效于标签中间放置文字。
- Inlines : 获取包含顶级 Inline 元素的 InlineCollection,前者构成 TextBlock 的内容。
<!--TextBlock Inlines的XML格式-->
<TextBlock Margin="5" TextWrapping="Wrap" TextAlignment="Center">
     This is a <Bold>TextBlock</Bold>,we are text the <Italic Foreground="Blue">inline elements</Italic>
     <Span TextDecorations="Underline" Background="Silver">Look me,Hahahaha</Span>
</TextBlock>

insert image description here

//TextBlock Inlines的代码格式
TextBlock textBlock1 = new TextBlock();

textBlock1.TextWrapping = TextWrapping.Wrap;
textBlock1.TextAlignment = TextAlignment.Center;

textBlock1.Inlines.Add("This is a");
textBlock1.Inlines.Add(new Blob(new Run("TextBlock")));
textBlock1.Inlines.Add(",we are text the");
textBlock1.Inlines.Add(new Italic(new Run("inline elements")){
    
     Foreground = Brushes.Blue });
...

2.2 Label

Label represents the text label of the control, similar to TextBlock. But the Label uses the Content property instead of the Text property. This is because any type of control can be placed inside the Label, not just text. Of course, the content can also be a string.

- 访问键/助记符:用于启用对控件的快速键盘访问,即通过访问键可以快速聚焦到相关的控件上。Label支持助记符绑定。
- Label助记符配置:在应为访问密钥的字符之前添加下划线,然后按住[Alt]键快速定位。 如果内容包含多个下划线字符,则只有第一个字符转换为访问键,其他下划线显示为普通文本。第一个下划线使用两个连续下划线表示普通的下划线文本内容。
- Foreground : 前景色背景
- Content : 设置Label内容,类型为Object
- Target : 获取或设置当用户按下标签的访问键时获得焦点的元素。
<Window x:Class="WpfTutorialSamples.Basic_controls.LabelControlAdvancedSample"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="LabelControlAdvancedSample" Height="180" Width="250">
    
	<StackPanel Margin="10">
		<Label Target="{Binding ElementName=txtName}">
            <!--Label内部Content包含堆叠对象-->
			<StackPanel Orientation="Horizontal">
				<Image Source="http://cdn1.iconfinder.com/data/icons/fatcow/16/bullet_green.png" />
                <!--AccessText控件用下划线来指定用作访问键的字符并呈现-->
				<AccessText Text="__Na_me:" />
			</StackPanel>
		</Label>
		<TextBox Name="txtName" />
		<Label Target="{Binding ElementName=txtMail}">
			<StackPanel Orientation="Horizontal">
				<Image Source="http://cdn1.iconfinder.com/data/icons/fatcow/16/bullet_blue.png" />
				<AccessText Text="_Mai_l:" />
			</StackPanel>
		</Label>
		<TextBox Name="txtMail" />
	</StackPanel>
    
</Window>

2.3 TextBox

The TextBox control is the most basic text input control in WPF. It allows displaying or editing unformatted text, like an editor.

- AcceptsReturn : 获取或设置一个值,该值指示在用户按 ENTER 键时文本编辑控件如何响应(如果按ENTER键可在当前光标位置处插入新行,则为true;否则将忽略ENTER键)
- TextWrapping : 获取或设置文本框中文本的换行方式
- Text : 获取或设置文本框的文本内容
- SpellCheck : 获取一个 SpellCheck 对象,来设置拼写检查错误
- Language : 该属性指示拼写检查器使用的语言
- IsReadOnly : 文本框是否只读
- TextBox的选择参数属性:
	- SelectionStart : 获取或设置当前选择的起始位置的字符索引(当前光标位置或是否有选择)
	- SelectionLength : 获取或设置一个值,该值指示文本框中当前选择的字符数(当前选择的长度,否则为0)
	- SelectedText : 获取或设置文本框中当前选择的内容(当前选择的字符串,否则为空)
- SelectionChanged : 订阅SelectionChanged事件,在文本选择改变时发生
<Window x:Class="WpfTutorialSamples.Basic_controls.TextBoxSelectionSample"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="TextBoxSelectionSample" Height="150" Width="300">
	<DockPanel Margin="10">
		<TextBox SelectionChanged="TextBox_SelectionChanged" DockPanel.Dock="Top" />
		<TextBox Name="txtStatus" AcceptsReturn="True" TextWrapping="Wrap" IsReadOnly="True" />
	</DockPanel>
</Window>
namespace WpfTutorialSamples.Basic_controls
{
    
    
	public partial class TextBoxSelectionSample : Window
	{
    
    
		public TextBoxSelectionSample()
		{
    
    
			InitializeComponent();
		}

		private void TextBox_SelectionChanged(object sender, RoutedEventArgs e)
		{
    
    
			TextBox textBox = sender as TextBox;
			txtStatus.Text = "Selection starts at character #" + textBox.SelectionStart + Environment.NewLine;
			txtStatus.Text += "Selection is " + textBox.SelectionLength + " character(s) long" + Environment.NewLine;
			txtStatus.Text += "Selected text: '" + textBox.SelectedText + "'";
		}
	}
}

img

2.4 Button

​ Button represents a Windows button control that can respond to the Click event. To apply the same property settings to multiple Button controls, use the Style property. You can also modify the default ControlTemplate to give the control a unique appearance.

- Content : 设置Button内容,类型为Object。可以包括字符串或一些复杂类型
- Foreground, Background, FontWeight : 设置Button控件文字的样式
- Padding : 获取或设置控件内部的填充边距
- 事件
	- Click : 在单击 Button 时发生事件
	- ClickMode : 获取或设置 Click 事件何时发生。
<Button Padding="5">  
    <StackPanel Orientation="Horizontal">  
    <Image Source="/WpfTutorialSamples;component/Images/help.png" />  
    <TextBlock Margin="5,0">Help</TextBlock>  
    </StackPanel>  
</Button>

img

2.5 List Collection Control

A list collection control represents a control that can be used to present a set of items/data. The list collection controls in WPF are derived from the ItemsControl class and belong to the elements of the ItemsControl family, such as ListBox and ComboBox. Here we take ItemsControl and ListBox as examples for control analysis.

(1)ItemsControl

​ ItemsControl is the simplest data list presentation control, which almost simply traverses and presents list data without providing any other item selection (ListBox can perform item selection). ItemsControl inherits from the Control class, so its list collection data is essentially just a piece of Content contained in the control. In addition to being the top-level element of the ItemsControl family, ItemsControl is often used as a custom list control (definition template).

  • Automatic wrapping of the ItemsControl family

​ - The most distinctive feature of the ItemsControl family is that it will automatically use the item container (Item Container) to wrap each data content of its list collection. Each ItemsControl type has its corresponding item container type. For example, the Item Container of ListBox is a ListBoxItem control; the Item Container of ComboBox is a ComboBoxItem control.

​ - Item Container is essentially a control element, most of which inherit from the ContentControl class (such as ListBoxItem), which also means that it can contain a single object of any type (such as a string, image or panel).

​ - When we submit the collection data as content to ItemsControl, ItemsControl will not use this collection directly, but first use the corresponding Item Container control to package each item of data in the collection one by one, and then pack the packaged The Item Container List is presented as the overall content of the ItemsControl. The advantage of this is that we can not only define the appearance of ItemsControl, but also conveniently define the appearance of each item of data! And the collection data type of ItemsControl can be various.

​ - An Item Container can be explicitly created for each data item in the ItemsControl , but this is not required. Because if the item container Item Container is not explicitly created, ItemsControl will automatically wrap the Item Container for each data item content.

 <ListBox>
	<ListBoxItem>ListBox Item 1</ListBoxItem>
	<ListBoxItem>ListBox Item 2</ListBoxItem>
	<ListBoxItem>ListBox Item 3</ListBoxItem>
	<ListBoxItem>ListBox Item 4</ListBoxItem>
</ListBox>

<!--              等价于            -->

<ListBox>
	<system:String>ListBox Item 1</system:String>
	<system:String>ListBox Item 2</system:String>
	<system:String>ListBox Item 3</system:String>
	<system:String>ListBox Item 4</system:String>
</ListBox>
  • ItemsControl class properties
public class ItemsControl : Control,IContainItemStorage,IAddChild
- 属性:
	- DataContext: 获取或设置元素参与数据绑定时的数据上下文。
	- DisplayMemberPath: 获取或设置源对象上的值的路径,以用作对象的可视表示形式。(只能显示简单的字符串数据)
	- HasItems: 获取一个值,该值指示 ItemsControl 是否包含项。
	- ItemContainerStyle: 获取或设置应用于为每个项生成的容器元素的 Style(设置其Item Container的Style)。
	- Items: 获取用于生成 ItemsControl 的内容的集合。
	- ItemsPanel: 获取或设置模板,该模板定义对项的布局进行控制的面板(默认值是一个纵向排列的指定StackPanel)
	- ItemsSource: 获取或设置用于生成 ItemsControl 的内容的集合(常用于数据绑定,ItemsSource设置属性后,集合Items是只读且固定大小)
	- ItemStringFormat: 获取或设置一个复合/格式化字符串,如果 ItemsControl 中的项显示为字符串,则用于指定如何格式化这些项。(仅用于string数据项)
	- ItemTemplate: 获取或设置用来显示[每个项]的 DataTemplate。
	- Template: 获取或设置控件模板。(整个ItemsControl的样式模板,非数据项)

(2)ListBox

​ The ListBox control inherits from the Selector under the ItemsControl. In addition to displaying a set of data elements in a list, the ListBox can also allow users to [select items] from its child elements.

public class ListBox : Selector
- 属性:
	- 继承 ItemsControl 的大部分属性
	- SelectedIndex: 获取或设置当前选择中第一项的索引,如果选择为空,则返回负一(-1)。
	- SelectedItem: 获取或设置当前选择中的第一项(Object),或者,如果选择为空,则返回 null。
	- SelectedItems: 获取当前选定的所有项集合(IList)。
	- SelectedValue: 获取或设置通过使用 SelectedValuePath 而获取的 SelectedItem 的路径值。当调用SelectedValue时,ListBox先找到选中的Item所对应的数据对象,然后把SelectedValuePath的值当作数据对象的属性名称并把这个属性值取出来。
	- SelectedValuePath: 获取或设置用于从 SelectedItem 中获取 SelectedValue 的路径/属性名(string)。
	- SelectionMode: 获取或设置 ListBox 的选择行为。默认值为 Single 选择。
		- Extended: 用户可以按下 Shift 键来选择多个连续项。
		- Multiple: 用户可以选择多个项而无需按下修改键。
		- Single: 用户一次只能选择一项。
- 事件:
	- SelectionChanged:当 Selector 的选择更改时发生。
namespace WPF_Demo
{
    
    
    public partial class MainWindow : Window
    {
    
    
        public MainWindow()
        {
    
    
            InitializeComponent();

            List<Employee> empList = new List<Employee>()
            {
    
    
                new Employee(){
    
    Id=1,Name="Tim",Age=30},
                new Employee(){
    
    Id=2,Name="Tom",Age=26},
                new Employee(){
    
    Id=3,Name="Kitty",Age=28},
                new Employee(){
    
    Id=4,Name="Lisa",Age=30},
                new Employee(){
    
    Id=5,Name="Krito",Age=36}
            };

            this.listBoxEmplyee.DisplayMemberPath = "Name";
            this.listBoxEmplyee.SelectedValuePath = "Id";
            this.listBoxEmplyee.ItemsSource = empList;
        }

        private void listBoxEmplyee_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
    
    
            ListBox lst = sender as ListBox;
            if (lst != null)
            {
    
    
                int id = (int)lst.SelectedValue;
                int index = lst.SelectedIndex;
                MessageBox.Show("Id=" + id + ",Index=" + index);
            }
        }
    }


    public class Employee
    {
    
    
        public int Id {
    
     get; set; }
        public string Name {
    
     get; set; }
        public int Age {
    
     get; set; }
    }

}

insert image description here

3. Common properties of common controls in WPF

3.1 ToolTip prompt object

The FrameworkElement class has a ToolTip property from which almost all WPF controls inherit. This property is used to get or set the tooltip object (UI, Object) displayed for this element in the user interface, such as a simple prompt string or a complex prompt layout. In addition, combined with the ToolTipService class, a bunch of interesting behaviors that affect the tooltip can be implemented, such as the ShowDuration property extending the time of the tooltip, etc.

<Window x:Class="WpfTutorialSamples.Control_concepts.ToolTipsAdvancedSample"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="ToolTipsAdvancedSample" Height="200" Width="400" UseLayoutRounding="True">
    <DockPanel>
        <ToolBar DockPanel.Dock="Top">
        	<!--简单字符串提示-->
            <Button ToolTip="Create a new file">
                <Button.Content>
                    <Image Source="/WpfTutorialSamples;component/Images/page_white.png" Width="16" Height="16" />
                </Button.Content>
            </Button>
            <Button>
                <Button.Content>
                    <Image Source="/WpfTutorialSamples;component/Images/folder.png" Width="16" Height="16" />
                </Button.Content>
                <!--复杂提示对象,布局Panel-->
                <Button.ToolTip>
                    <StackPanel>
                        <TextBlock FontWeight="Bold" FontSize="14" Margin="0,0,0,5">Open file</TextBlock>
                        <TextBlock>
                        Search your computer or local network
                        <LineBreak />
                        for a file and open it for editing.
                        </TextBlock>
                        <Border BorderBrush="Silver" BorderThickness="0,1,0,0" Margin="0,8" />
                        <WrapPanel>
                            <Image Source="/WpfTutorialSamples;component/Images/help.png" Margin="0,0,5,0" />
                            <TextBlock FontStyle="Italic">Press F1 for more help</TextBlock>
                        </WrapPanel>
                    </StackPanel>
                </Button.ToolTip>
            </Button>
        </ToolBar>

        <TextBox>
            Editor area...
        </TextBox>
    </DockPanel>
</Window>

img

3.2 Text Rendering

Microsoft made a lot of optimizations for the WPF text rendering engine in .NET Framework 4.0, introducing the TextOptions class and related properties

- TextOptions.TextFormattingMode : 选择用 Ideal(默认值)或 Display(更清晰)
- TextOptions.TextRenderingMode : 控制显示文本所用的抗锯齿算法
<Label TextOptions.TextFormattingMode="Display" FontSize="9">TextFormattingMode.Ideal, small text</Label>
<Label TextOptions.TextRenderingMode="Auto" FontSize="9">TextRenderingMode.Auto, small text</Label>

2. Resources and converters

1. WPF resources

1.1 Resource Definition

A resource is a collection of object data that can be reused in different places in the application. All data, controls, strings, etc. can be stored as resources, which enables you to store data in one place and use it anywhere, which is very practical. The interface elements of WPF all have a Resources attribute, whose type is ResourceDictionary, which can store data resources in the form of "key-value" pairs. Each resource in a resource dictionary must have a unique key. A unique key can be assigned via the x:Key directive when defining a resource in markup. Typically, this key is a string.

(1) Control scope: The resource dictionary defined by the control can only be used inside the current control <StackPanel.Resources>…</StackPanel.Resources>

(2) Window/page scope: <Window.Resources> ...</Window.Resources> can only be used in the current window/page

(3) Global application: globally available <Application.Resources>…</Application.Resources>

1.2 Resource usage

WPF will automatically search for the specified resource from the current area control item (control range) to the window and then to App.xaml along the UI tree from bottom to top, and stop when it finds it, but it will not search downward. Resources and resource dictionaries can not only define the style of elements, but also define resource templates, storyboards, triggers, etc., which facilitates code redundancy and repeated definition of the same style when defining styles for many same controls.

  • Static resources: lookup at compile time , by using the StaticResource markup extension to create references (using markup extensions to process attribute strings and return objects to XAML loaders, thereby specifying object references/binding reference objects), static resource references will only be in the program Loaded once at runtime.

  • Dynamic Resources: Lookup at runtime , create references by using the DynamicResource markup extension. Creates a temporary expression during initial compilation, thereby deferring the lookup of the resource until the requested resource value is actually needed in order to construct the object. Lookup for this resource behaves like a runtime lookup, which affects performance . Use static resources as much as possible in your application and use dynamic resources only when necessary.

(1) XAML declaration:<子元素 (对应)属性名=”{StaticResource 资源标记名}” /> or <子元素 (对应)属性名=”{DynamicResource 资源标记名}” />XAML automatically matches the data type, no need to force conversion, and an exception will be thrown when the type does not match.

(2) Code reference:

  • string text = (string)this.FindResource("str");The resource dictionary value is Object, which needs to be forcibly converted. The FindResource method is to search upwards from the bottom of the UI tree

  • string text1 = (string)this.Resources["str"]; The resource dictionary value is Object, which needs to be forcibly converted. The Resources method is to only search for the resource dictionary of this control

1.3 Resource Merging

(1) Define resource dictionary

In addition to defining local resource dictionaries inside the above controls/windows, we can also define resource dictionaries independently for use between different applications/different projects. The ResourceDictionary class provides a hashtable/dictionary implementation (Map of key-value pairs) that contains WPF resources used by components and other elements of a WPF application. VS2019 provides a creation item for adding a resource dictionary.xaml file . The resource dictionary is written in the same way as resources, just define your resources directly in the file.

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:WPF_Demo">

    <Style TargetType="TextBox">
        <Setter Property="FontFamily" Value="楷体"></Setter>
        <Setter Property="FontSize" Value="50"></Setter>
        <Setter Property="Foreground" Value="Red"></Setter>
    </Style>
</ResourceDictionary>

(2) Resource merging

​ The newly defined independent resource dictionary cannot be used directly, because the dictionary cannot be recognized by WPF yet, we need to merge and add it to the corresponding control/window/APP range, and the merge property used is MergedDictionaries . MergedDictionaries is a property of the ResourceDictionary class, which is a ResourceDictionary collection type.

Typically, each ResourceDictionary in the MergedDictionaries collection specifies a Source property. The value of Source should be a Uniform Resource Identifier (URI) that resolves to the location of the resource file to be merged. The target of this URI must be another XAML file with a ResourceDictionary as its root element.

  • Merge in single project
<ResourceDictionary>
     <ResourceDictionary.MergedDictionaries>
         <!--<ResourceDictionary Source="资源字典路径"/>-->
           <ResourceDictionary Source="/Dictionarys/ColorDictionary.xaml"/>
           <ResourceDictionary Source="..."/>
     </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
  • Merge in multiple projects
<ResourceDictionary>
    <ResourceDictionary.MergedDictionaries>
       <!--<ResourceDictionary Source="/项目名;component/资源字典路径"/>-->
       <ResourceDictionary Source="/CommonModel;component/Dictionarys/PathDictionary.xaml"/>
       <ResourceDictionary Source="..."/>
    </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>

2. Type Converter

References:

2.1 The concept of converter

​ Value converters are often used together with data binding to custom convert data between different types and display them on the bound UI. The WPF data converter needs to implement the IValueConverter interface , or the IMultiValueConverter interface (multi-way binding). Only two methods need to be implemented: Convert() and ConvertBack() are used to convert the value to the target format and back again.

namespace System.Windows.Data
{
    
    
    public interface IValueConverter
    {
    
    
        // 摘要: 数据绑定引擎在将值从绑定源传播到绑定目标时会调用此方法,即源属性传给目标属性时
        // 参数:
        //   value: 绑定源生成的值。
        //   targetType: 绑定目标属性的类型。
        //   parameter: 要使用的转换器参数。
        //   culture: 要用在转换器中的区域化/国际化信息。
        // 返回结果:
        //     转换后的值。 如果该方法返回 null,则使用有效的 null 值。
        object Convert(object value, Type targetType, object parameter, CultureInfo culture);

        // 摘要: 数据绑定引擎在将值从绑定目标传播到绑定源时调用此方法,此方法的实现必须是Convert方法的反向实现。
        // 参数:
        //   value: 绑定源生成的值。
        //   targetType: 绑定目标属性的类型。
        //   parameter: 要使用的转换器参数。
        //   culture: 要用在转换器中的区域化/国际化信息。
        // 返回结果:
        //     转换后的值。 如果该方法返回 null,则使用有效的 null 值。
        object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture);
    }
}

2.2 Converter Implementation Example

Background: bind the string, automatically convert the corresponding color and display it on the UI, the specific implementation is as follows

(1) Converter implementation

namespace WPF_Demo.Convert
{
    
    
    [ValueConversion(typeof(string), typeof(SolidColorBrush))]
    class DemoConvert : IValueConverter
    {
    
    
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
    
    
            string str = value.ToString().ToLower();
            if (str.Equals("x-red"))
            {
    
    
                return new SolidColorBrush(Color.FromRgb(222, 32,37));
            }else if (str.Equals("x-blue"))
            {
    
    
                return new SolidColorBrush(Color.FromRgb(19, 21, 190));
            }
            return new SolidColorBrush(Color.FromRgb(0, 0, 0));
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
    
    
            throw new NotImplementedException();
        }
    }
}

(2) Use of XAML interface

  • Introduce the Convert namespace: xmlns:cv="clr-namespace:WPF_Demo.Converts"
  • Add Window resource: <cv:StringToColorConvert x:Key="bgCV"/>
  • Binding data conversion: Background="{Binding} ElementName=txt,Path=Text,Converter={StaticResource bgCV}}"
<Window x:Class="WPF_Demo.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:WPF_Demo"
        xmlns:cv="clr-namespace:WPF_Demo.Converts"  
        mc:Ignorable="d"
        Title="MainWindow" Height="250" Width="400">
    <Window.Resources>
        <cv:StringToColorConvert x:Key="bgCV"/>
    </Window.Resources>
    
    <StackPanel Margin="10">
        <TextBox x:Name="txt" Margin="10" Text="x-blue"/>
        <TextBlock Height="50" Margin="10" Background="{Binding ElementName=txt,Path=Text,Converter={StaticResource bgCV}}"/>
    </StackPanel>
</Window>

3. Basic layout introduction

Common layout additional attributes for layout child elements:

  • VerticalAlignment: This property is used to get or set the vertical alignment characteristics applied when combining this element in a parent element (such as a Panel or item control)
  • HorizontalAlignment: This property is used to get or set the horizontal alignment characteristics applied when combining this element in a parent element (such as a Panel or item control)

1 StackPanel stack layout

(1) Concept: StackPanel is a stack layout, which arranges its child elements in a horizontal or vertical row. StackPanel contains a collection of UIElement objects (a collection of child elements), which are located in the property Children.

- Orientation : 获取或设置一个值,该值指示子元素的堆叠维度(方向),其中 Horizontal水平,Vertical垂直
- Children : 获取此Panel的 UIElementCollection 子元素集合(继承自 Panel)
- CanVerticallyScroll : 获取或设置一个值,该值指示内容能否垂直滚动。
- CanHorizontallyScroll : 获取或设置一个值,该值指示 StackPanel 能否水平滚动。
<Window x:Class="WpfTutorialSamples.Panels.StackPanel"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="StackPanel" Height="160" Width="300">
	<StackPanel Orientation="Horizontal">
		<Button VerticalAlignment="Top">Button 1</Button>
		<Button VerticalAlignment="Center">Button 2</Button>
		<Button VerticalAlignment="Bottom">Button 3</Button>
		<Button VerticalAlignment="Bottom">Button 4</Button>
		<Button VerticalAlignment="Center">Button 5</Button>
		<Button VerticalAlignment="Top">Button 6</Button>
	</StackPanel>
</Window>

(2) Scrolling: StackPanel does not provide physical scrolling of content by default. If physical scrolling is required instead of logical scrolling, please wrap the StackPanel element in a ScrollViewer control and set its CanContentScroll property to false.

2 Grid grid layout

(1) Concept: Grid is a grid layout used to define a flexible grid area composed of columns and rows. Grid contains a collection of UIElement objects (a collection of child elements), which are located in the property Children. Grid child elements are drawn in the order shown in markup or code. , so a hierarchical display order (also known as z-order) can be achieved when elements share the same coordinates.

- Children : 获取此Panel的 UIElementCollection 子元素集合(继承自 Panel)
- ColumnDefinitions : 获取在 Grid 的实例上定义的 ColumnDefinitionCollection 列的定义信息集合
	- ColumnDefinition : 定义将应用于 Grid 元素的特定于列的属性,每个 ColumnDefinition 都成为表示最终网格布局中的列的占位符。
		- Width : 获取或设置 ColumnDefinition 定义的列的宽度值, GridLength 对象
			- 单位(Star) * : 占用剩余的空间按比例划分,宽度2*是1*的两倍
			- 单位(Auto) Auto : 该大小由内容对象元素的大小属性确定
			- 单位(Pixel) 像素绝对值 : 该值表示为一个绝对的像素值
- RowDefinitions : 获取在 Grid 的实例上定义的 RowDefinitionCollection 行的定义信息集合,
	- RowDefinition : 定义将应用于 Grid 元素的特定于行的属性, 每个 RowDefinition 都成为表示最终网格布局中的行的占位符。
		- Height : 获取或设置 RowDefinition 定义的行的高度值, GridLength 对象
			- 单位(Star) * : 占用剩余的空间按比例划分,宽度2*是1*的两倍
			- 单位(Auto) Auto : 该大小由内容对象元素的大小属性确定
			- 单位(Pixel) 像素绝对值 : 该值表示为一个绝对的像素值
- ShowGridLines : 获取或设置一个值,该值指示网格线在此 Grid 中是否可见

(2) Attached attribute (Attached): An attached attribute is a special dependency attribute for a class that does not define the attribute. For example, RowDefinition, ColumnDefinition of Grid panel, Left and Right of Canvas panel, etc.

- Column : 获取或设置一个值,该值表示 Grid 中的子内容所在的列,从0开始下同
- ColumnSpan : 获取或设置一个值,该值指示 Grid 中的子内容所跨越的总列数。默认1
- Row : 获取或设置一个值,该值表示 Grid 中的子内容所在的行
- RowSpan : 获取或设置一个值,该值表示在一个 Grid 中子内容所跨越的总行数。默认1
<Window x:Class="WpfTutorialSamples.Panels.GridColRowSpan"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="GridColRowSpan" Height="110" Width="300">
	<Grid>
		<Grid.ColumnDefinitions>			
			<ColumnDefinition Width="1*" />
			<ColumnDefinition Width="1*" />
		</Grid.ColumnDefinitions>
		<Grid.RowDefinitions>
			<RowDefinition Height="*" />
			<RowDefinition Height="*" />
		</Grid.RowDefinitions>
		<Button>Button 1</Button>
		<Button Grid.Column="1">Button 2</Button>
		<Button Grid.Row="1" Grid.ColumnSpan="2">Button 3</Button>
	</Grid>
</Window>

3 Canvas Canvas

Canvas inherits from Controls.Panel and is used to define an area in which child elements can be positioned explicitly using coordinates relative to the Canvas area. The characteristics of Canvas are as follows:

(1) The default value of the Height and Width properties of Canvas is 0. If you don't set these values, you won't see the canvas unless the child elements resize automatically.
(2) Child elements on the Canvas are never resized (as the form changes), they are just placed at specified coordinates. When you want to automatically adjust and align child content, it is best to use the Grid element.
(3) Vertical and horizontal alignment on child elements does not work. Child elements are placed only at positions set by the Canvas Left, Top, Right, and Bottom properties.
(4) Position priority: If the Left property of the Canvas is set, the Right property will have no effect. If the Canvas's Top property is set, the Bottom property will have no effect.

- 属性:
	- Children : 获取此Panel的 UIElementCollection 子元素集合(继承自 Panel)
	- Width: 获取或设置元素的宽度。(继承自 FrameworkElement)
	- Height: 获取或设置元素的建议高度。(继承自 FrameworkElement)
- 附加属性:
	- Bottom:获取或设置一个值,该值表示元素底部与其父 Canvas 底部之间的相对距离。(单位是像素)
	- Left:获取或设置一个值,该值表示元素左侧与其父 Canvas 左侧之间的距离。
	- Right:获取或设置一个值,该值表示元素右侧与其父 Canvas 右侧之间的距离。
	- Top:获取或设置一个值,该值表示元素顶部与其父 Canvas 顶部之间的距离。
	- Panel.ZIndex:获取或设置一个值,该值表示元素在 Z 平面中的显示顺序(上下深度顺序/层叠顺序)
		- ZIndex值越大显示优先级越高,允许负值,ZIndex的最大值为32766,默认值为0)。
		- 相同ZIndex则按照绘制/添加顺序,依次覆盖显示
<!--Canvas实例:XAML版本-->
<Window x:Class="WPF_Demo.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:WPF_Demo"
        xmlns:vm="clr-namespace:WPF_Demo.Status"
        xmlns:cm="clr-namespace:WPF_Demo.Commands"
        mc:Ignorable="d" 
        Title="MainWindow" Height="275" Width="260">
    <Canvas>
        <Ellipse Fill="Gainsboro"  Canvas.Left="25" Canvas.Top="25" Width="200" Height="200" />
        <Rectangle Fill="LightBlue" Panel.ZIndex="1" Canvas.Left="25" Canvas.Top="25" Width="50" Height="50" />
        <Rectangle Fill="LightCoral" Canvas.Left="50" Canvas.Top="50" Width="50" Height="50" />
        <Rectangle Fill="LightCyan" Panel.ZIndex="2" Canvas.Left="75" Canvas.Top="75" Width="50" Height="50" />
    </Canvas>
</Window>
//Canvas实例:代码版本
namespace WPF_Demo
{
    
    
    public partial class MainWindow : Window
    {
    
    
        public MainWindow()
        {
    
    
            InitializeComponent();
            //1.添加Ellipse对象
            Ellipse ellipse = new Ellipse();
            ellipse.Fill = new SolidColorBrush(Colors.Gainsboro);
            ellipse.Width = 200;
            ellipse.Height = 200;
            //Set Canvas position  
            Canvas.SetLeft(ellipse, 25);
            Canvas.SetTop(ellipse, 25);
            //Add Ellips to Canvas 
            this.canvas.Children.Add(ellipse);

            //2.添加Rectangle对象1
            Rectangle Red_rectangle = new Rectangle();
            Red_rectangle.Fill = new SolidColorBrush(Colors.Red);
            Red_rectangle.Width = 50;
            Red_rectangle.Height = 50;
            //Set Canvas position  
            Canvas.SetLeft(Red_rectangle, 25);
            Canvas.SetTop(Red_rectangle, 25);
            Panel.SetZIndex(Red_rectangle, 1);
            //Add Ellips to Canvas 
            this.canvas.Children.Add(Red_rectangle);
            
            //3.添加Rectangle对象2
            Rectangle Green_rectangle = new Rectangle();
            Green_rectangle.Fill = new SolidColorBrush(Colors.Green);
            Green_rectangle.Width = 50;
            Green_rectangle.Height = 50;
            //Set Canvas position  
            Canvas.SetLeft(Green_rectangle, 50);
            Canvas.SetTop(Green_rectangle, 50);
            //Add Ellips to Canvas 
            this.canvas.Children.Add(Green_rectangle);

            //4.添加Rectangle对象3
            Rectangle Yello_rectangle = new Rectangle();
            Yello_rectangle.Fill = new SolidColorBrush(Colors.Yellow);
            Yello_rectangle.Width = 50;
            Yello_rectangle.Height = 50;
            //Set Canvas position  
            Canvas.SetLeft(Yello_rectangle, 75);
            Canvas.SetTop(Yello_rectangle, 75);
            Panel.SetZIndex(Yello_rectangle, 2);
            //Add Ellips to Canvas 
            this.canvas.Children.Add(Yello_rectangle);
        }
    }

}

Guess you like

Origin blog.csdn.net/qq_40772692/article/details/126426982