zoukankan      html  css  js  c++  java
  • WPF控件和布局

      WPF控件和布局,根据刘铁猛《深入浅出WPF》书籍讲解内容,主要记录控件和布局的原理,如果有不足的地方,请大牛们键盘下留情--轻喷!如果还算有用,请给点动力,支持一把!

    一、WPF里的控件

    1.1 控件的实质

      我们先从UI上分析,UI的功能是让用户观察和操作数据,为了能显示数据和响应用户的操作通知程序(通过事件来通知,如何处理事件又是一系列的算法),所以控件就是显示数据和响应用户操作的UI元素,也即:控件就是数据和行为的载体。 

    1.2 WPF中的一个重要概念--数据驱动UI

      什么是数据驱动UI呢?我们知道传统的GUI界面都是由windows消息通过事件传递给程序,程序根据不同的操作来表达出不同的数据体现在UI界面上,这样数据在某种程度上来说,受到很大的限制。WPF中是数据驱动UI,数据是核心,处于主动的,UI从属于数据并表达数据,是被动的。因为以后的章节会重点介绍,在此不做过多的说明,只要记着,WPF数据第一,控件第二。

    1.3 WPF中控件的知多少

      虽然控件没有数据重要,但是还是比较重要的,毕竟是门面啊,只是在数据面前,它比较"有礼貌"。控件有很多,但是如果仔细去分析,也是有规律可循的,根据其作用,我们可以把控件分为6类:

    • 布局控件:是可以容纳多个控件或者嵌套其他布局的控件,用于在UI上组织和排列控件。其父类为Panel。
    • 内容控件:只能容纳一个控件或者布局控件作为他的内容。所以经常借助布局控件来规划其内容。其父类为ContentControl。
    • 带标题内容控件:相当于一个内容控件,但是可以加一个标题,标题部分也可以容纳一个控件或者布局,其父类为HeaderedContentControl。
    • 条目控件:可以显示一列数据,一般情况下,是数据的类型是相同的。其共同的基类为ItemsControl。
    • 带标题的条目控件:和上面的带标题内容控件类同,其基类为HeaderdeItemsControl。
    • 特殊内容控件:这类控件比较独立,但也比较常用,如TextBox,TextBlock,Image等(由于其常用性和相对比较简单,本篇笔记不做说明)。

    上面的控件的派生关系如图1:

    图1

    二、各类控件模型详解

    2.1 WPF中的内容模型  

      为了理解各个控件的模型,还是先了解一下WPF中的内容模型。在上述各类控件里,至少可以容纳一个内容,主要原因是由于每个控件对象都会有一个重要又不常写出来的属性--Content Property(有Content,Child,Items,Children几个属性,如Grid可以容纳多个控件,用的是Children)。内容模型就是每一族的控件都含有一个或者多个元素作为其内容(其下面的元素可能是其他控件)。为什么可以不常写出来呢?先让我们看下面两段代码:

    XAML Code
    <Window x:Class="Chapter_03.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="内容属性测试" Height="350" Width="525">
        <Grid>
            <Grid.Children>
                <Button Content="1"  Margin="120,146,0,146" HorizontalAlignment="Left" Width="82" />
                <Button Content="2" x:Name="btn2" Margin="0,146,142,145" HorizontalAlignment="Right" Width="82" />
            </Grid.Children>
        </Grid>
    </Window>
    XAML
    <Window x:Class="Chapter_03.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="内容属性测试" Height="350" Width="525">
        <Grid>
    
                <Button Content="1"  Margin="120,146,0,146" HorizontalAlignment="Left" Width="82" />
                <Button Content="2" x:Name="btn2" Margin="0,146,142,145" HorizontalAlignment="Right" Width="82" />
    
        </Grid>
    </Window>

    运行两段代码效果一样。充分说明了重要而有不常见的原因。因为省略的省时,而且简洁明了。所以多数引用时都省去了。

    2.2ContentControl族

      先说一下其特点:他们内容属性的名称为Content,只能有单一元素充当其内容。下面通过例子说明其特点:

            <Button Margin="120,146,0,76" HorizontalAlignment="Left" Width="100">
                <TextBox Text="测试"/>
                <TextBox Text="测试"/>
                <TextBox Text="测试"/>
            </Button>

    上面的会报错,原因是Button里面只能有单一元素充当其内容。去掉后面的两个TextBox,效果如图2:

    图2

    发现button里面不仅可以显示文字还可以用一个控件来当其内容。其他的控件不在一一举例。在此列出此类的主要控件:

    Button、ButtonBase、CheckBox、ComboBoxItem、ContentControl、Frame、GridViewColumnHeader、GropItem、Label、ListBoxItem、ListViewItem、NavigationWindow、RadioButton、ScrollViewer、StatusBarItem、ToggleButton、ToolTip、UserControl、Window。

    2.3 HeaderedContentControl族

      特点:可以显示带标题的数据,内容属性为Content和Header,其这两个属性都只能容纳一个元素。在此举例说明GroupBox的用法,然后列出其他属于此类的控件。XAML代码为:

    View Code
    <Window x:Class="Chapter_03.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="内容属性测试" Height="200" Width="300">
        <Grid Background="Gold">
            <GroupBox Margin="42,0,96,26">
                <GroupBox.Header>
                    <Label Content="我是标题"/>
                </GroupBox.Header>
            <Button  HorizontalAlignment="Left" Width="117" Height="45">
                <TextBox Text="测试"/>
            </Button>
            </GroupBox>
        </Grid>
    </Window>

    效果图如图3:

    图3

    是不是看着很还好呢?现在列出同类主要的控件:Expender,GroupBox,HeaderedContentControl,TabItem。

    2.4 ItemsControl族

      特点:该类控件用于显示列表化的数据,内容属性为Items或ItemsSource,每种ItemsControl都对应有自己的条目容器(Item Container)。本类元素可能会用的比较多些,也比较灵活,所以这里不做过多记录,以后的记录会经常用到,具体的再详细说明。下面就用一个ListBox控件来小试牛刀吧!XAML代码、Cs代码如下:

    XAML
    <Window x:Class="Chapter_03.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="内容属性测试" Height="260" Width="408">
        <Grid Background="Gold">
            <ListBox x:Name="listbox" Margin="0,0,198,55">
                    <CheckBox x:Name="cb1" Content="选择"/>
                    <CheckBox x:Name="cb2" Content="选择"/>
                    <CheckBox x:Name="cb3" Content="选择"/>
                    <CheckBox x:Name="cb4" Content="选择"/>
                    <Button x:Name="btn1" Content="按钮1"/>
                    <Button x:Name="btn2" Content="按钮1"/>
                    <Button x:Name="btn3" Content="按钮1"/>
            </ListBox>
        </Grid>
    </Window>
    CS
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Navigation;
    using System.Windows.Shapes;
    
    namespace Chapter_03
    {
        /// <summary>
        /// MainWindow.xaml 的交互逻辑
        /// </summary>
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
                Button btn=new  Button();
                btn.Content="另外添加一个";
                btn.Click += new RoutedEventHandler(btn_Click);
                this.listbox.Items.Add(btn);
                btn3.Click+=new RoutedEventHandler(btn_Click);
            }
            /// <summary>
            /// 用来找到button的父级元素类型
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            void btn_Click(object sender, RoutedEventArgs e)
            {
                Button btn=(sender) as Button;
                DependencyObject level1 = VisualTreeHelper.GetParent(btn);
                DependencyObject level2 = VisualTreeHelper.GetParent(level1);
                DependencyObject level3 = VisualTreeHelper.GetParent(level2);
                if (btn != null)
                    MessageBox.Show(level3.GetType().ToString());
                else MessageBox.Show("无找到!");
            }
        }
    }

    效果图如图4:

    图4

       先来说明一下代码:在listBox里面放了几个checkbox和button,说明ListBoxI的Item不仅支持类型相同的元素,还支持类型不同的元素。这是因为,Listbox的每一项都是经过“ListBoxItem”加工厂处理的,最终放入当做自己的内容--放入自己的容器内。这里通过后台代码说明了每一个条目都被ListboxItem包装过了,完全没有必要每一个条目都在xmal文件按照如下写法:

                <ListBoxItem>
                    <Button x:Name="btn3" Content="按钮1"/>
                </ListBoxItem>

      在实际项目中,很少像上面那样把代码写死,可以动态的绑定ListBox。把数据源赋给ListBox的ItemsSource,通过DisplayMemberPath属性来显示string类型的数据源里面的字段条目(如果想显示复杂的数据的话,要使用DataTemplate,具体在模板再记录,在此知道有这么一回事就好了);通过SelectedItem和SelectionChanged来观察选中的项。下面的例子实现在listbox上绑定指定数据,然后弹出选中人的年龄。直接给出代码:

    XAML
    <Window x:Class="Chapter_03.ListBoxTest"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="ListBoxTest" Height="300" Width="300">
        <Grid>
            <ListBox x:Name="listbox1" Margin="0,0,60,31" SelectionChanged="listbox1_SelectionChanged"></ListBox>
        </Grid>
    </Window>
    CS
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Shapes;
    
    namespace Chapter_03
    {
        /// <summary>
        /// ListBoxTest.xaml 的交互逻辑
        /// </summary>
        public partial class ListBoxTest : Window
        {
            public ListBoxTest()
            {
                InitializeComponent();
                InitData();
            }
            protected void InitData()
            {
                List<People> peopleList = new List<People>()
                {
                    new People(){Id=1,Name="Tim",Age=30},
                    new People(){Id=2,Name="Tom",Age=30},

    显示结果如图5:

    图5

      下面列出属于ItemsControl族元素和其对应的Item Container有ComboBox——ComboBoxItem,ContextMenu——MenuItem,ListBox——ListBoxItem,ListView——ListViewItem,Menu——MenuItem,StatusBar——StatusBarItem,TabControl——TabItem,TreeView——TreeViewItem.

      由于已经演示了HeaderedContentControl和ItemsControl的功能,另外HeaderedItemsControl的用法就不再记录了,仅仅列出属于其族的控件:

      MemuItem、TreeViewItem、TooBar。

    三、 UI布局

      在介绍布局之前还是先记录一下布局控件的特点与属于Panel族的控件。

      panel族控件内容属性为Children,所以内容可以是多个元素,这对布局来说是很重要的特征。布局控件与ItemControl的区别是:前者强调的是对元素的布局,后者强调的是条目。属于Panel类的控件有:Canvas,DockPanel,Grid,TabPanel,ToolBarOverflowPanel,StackPanel,ToolBarPanel,UniformGrid,VirtualizingPanel,VirtualizingStackPanel,WrapPanel。这么多控件不可能一个个去介绍,找几个比较重要的实践一下。回头如果有用到的话再逐一研究。

    3.1 主要布局控件的特性

      在WPF里面控件与控件的关系除了相邻和重叠(用Opacity来控制哪个控件在上面,哪个在下面),还有一个包含。正因为如此,才有了以window为根的树形结构的XAML。下面介绍一下主要布局元素的特性:

    • Grid:网格。可以自定义行和列,并通过行列的数量、行高和列宽来调整控件的布局,有点类似于html中的Table。
    • StackPanel:栈式面板。可以将包含元素排成一条直线,当添加或移除包含元素时,后面的元素会自动向下或向上移动。
    • Canvas:画布。可以指定包含元素的绝对坐标位置。
    • DockPanel:泊靠式面板。内部元素可以选择泊靠方式。
    • WarpPanel:自动折行面板。当一行元素排满后会自动换行。类似html中的流式布局。

    3.2 Grid

      Grid的特点如下:

    • 可以定义任意数量的行和列
    • 行高与列宽可以使用绝对值,相对比以及最大值和最小值
    • 内部元素可以设置自己的所在列和行,还可以设置自己跨几列和行。
    • 可以设置Children元素的对齐方式

      现在给出定义行与列的代码(记得在后台代码上加上 this.grid.ShowGridLines=true以便显示出网格):

    XAML
    <Window x:Class="Chapter_03.Grid"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="Grid" Height="300" Width="300" MinHeight="300" MaxWidth="500">
        <!--MinHeight="300" MaxWidth="500"限制窗口的最小高度和最大宽度-->
        <Grid x:Name="grid">
            <!--定义行-->
            <Grid.RowDefinitions>
                <RowDefinition Height="25" ></RowDefinition>
                <RowDefinition Height="50"/>
                <RowDefinition Height="1*"/>
                <RowDefinition Height="*"/>
                <RowDefinition Height="auto">
                </RowDefinition>
            </Grid.RowDefinitions>
            <!--定义列-->
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="25" ></ColumnDefinition>
                <ColumnDefinition Width="50"/>
                <ColumnDefinition Width="1*"/>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="auto"/>
            </Grid.ColumnDefinitions>
            <!--在指定的行列中布置控件-->
            <TextBox Grid.Column="1" Grid.Row="2" Grid.ColumnSpan="2" Text="布局" Background="Gray"/>
        </Grid>
    </Window>

    运行效果图如图6,可以放大观察效果(是因为Width="*"的原因,本例子中利用了两个*其中第三行是一个*,所以占剩余的二分之一,可以试着改成2*,就是三分之二了,可以试着观察效果):

    图6

     3.3 StackPanel

      StackPanel可以把内部的元素在纵向或者横向上紧密排列,形成栈式布局。先介绍一下其三个属性:

    • Orientation 决定内部元素是横向还是纵向累积。可取值为Horizontal,Vertical。
    • HorizontalAlignment 决定内部元素水平方向上的对齐方式。可取值Left,Center,Right,Stretch。
    • VerticalAlignment 决定内部元素竖直方向上的对齐方式。可取Top,Center,Bottom,Stretch。

    StackPanel也是布局中比较常见的控件,下面举例:添加按钮,其他内容控件会自动下移。效果如图7:

    图7

    下面上代码:

    XAML
    <Window x:Class="Chapter_03.StackPanel"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="StackPanel" Height="338" Width="423">
        <Grid Height="286" Width="382">
            <GroupBox Header="测试StackPanel" BorderBrush="Black" Margin="5">
                <StackPanel Margin="5" x:Name="stackpanel">
                    <StackPanel Orientation="Vertical" x:Name="btnList"></StackPanel>
                    <StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
                        <TextBlock Text="填写添加按钮名称: " Height="20" />
                        <TextBox Name="btnName" Width="102" Height="20" />
                        <Button Content="添加" Width="60" Margin="5" Click="Button_Click" />
                    </StackPanel>
                </StackPanel>
                
            </GroupBox>
            
        </Grid>
    </Window>
    Cs
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Shapes;
    
    namespace Chapter_03
    {
        /// <summary>
        /// StackPane_.xaml 的交互逻辑
        /// </summary>
        public partial class StackPanel : Window
        {
            public StackPanel()
            {
                InitializeComponent();
            }
    
            private void Button_Click(object sender, RoutedEventArgs e)
            {
                if (!string.IsNullOrEmpty(this.btnName.Text))
                {
                    Button btn = new Button();
                    btn.Content = this.btnName.Text;
                    this.btnList.Children.Add(btn);
                }
                else
                    MessageBox.Show("请输入按钮名称!");
            }
        }
    }

    当输入按钮名称的话,点击添加,原有的内容会下移。

    3.4 Canvas  

      画布:内容控件可以准确定位到指定坐标,但是不足的地方是,如果要修改的话可能会关系到很多的控件,所以如果不需要经常修改的窗体,使用该控件布局,或者是艺术性比较强(用来实现依赖于横纵坐标的动画等功能)的布局使用此控件布局。

      在此制作一个登陆页面主要来看一下Canvas.Left与Canvas.Top的用法。效果图如图8,直接上代码:

    XAML
    <Window x:Class="Chapter_03.Canvas"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="登陆" Height="145" Width="300">
        <Canvas Background="Sienna">
            <TextBlock  Canvas.Left="0" Canvas.Top="13" Margin="5" Text="用户名:"/>
            <TextBox Canvas.Left="50" Canvas.Top="13" Width="160" />
            <TextBlock  Canvas.Left="0" Canvas.Top="47" Margin="5" Text="密  码:"/>
            <TextBox Canvas.Left="50" Canvas.Top="47" Width="160" />
            <Button Content="确定" Canvas.Left="70" Canvas.Top="77"  Width="63" Height="22" />
            <Button Canvas.Left="150" Canvas.Top="77" Content="清除"  Width="63" Height="22" />
        </Canvas>
    </Window>

     图8

    3.5 DockPanel

      这个控件主要有个最后一个内容控件实现填充所有剩余部分的功能。主要用到LastChildFill=True属性。下面给出一个例子,先看一下把LastChildFill分别设置为True和False的结果对比图如图9:

    图9

    XAML代码给出: 

    XAML
    <Window x:Class="Chapter_03.DockPanel"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="DockPanel" Height="300" Width="300">
        <DockPanel Name="dockpanel" LastChildFill="True">
            <Button Name="button1" DockPanel.Dock="Top">1</Button>
            <Button Name="button2" DockPanel.Dock="Bottom" >2</Button>
            <Button Name="button3" DockPanel.Dock="Left">3</Button>
            <Button Name="button4" DockPanel.Dock="Right">4</Button>
            <Button DockPanel.Dock="Top">剩余空间</Button>
        </DockPanel>
    
    </Window>

      在此说明一下,如果LastChildFill=True,最后一个元素 <Button >剩余空间</Button>就会充满其剩余部分。上面的只能填充,但是不能通过拖拽的方式改变控件的宽度。下面给出一个实现拖拽功能的代码。不过是在Grid里面的通过GridSplitter(可以改变Grid初始设置的行高或列宽)控件实现。直接给出代码:

    XAML
    <Window x:Class="Chapter_03.GridSplitter"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="GridSplitter" Height="300" Width="300">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="5"/>
                <RowDefinition/>
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="150"/>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition/>
            </Grid.ColumnDefinitions>
            <TextBox Grid.ColumnSpan="3" BorderBrush="Black"/>
            <TextBox Grid.Row="1" BorderBrush="Black"/>
            <GridSplitter Grid.Row="1" Grid.Column="1" VerticalAlignment="Stretch" HorizontalAlignment="Center"
                          Width="5" Background="Gray" ShowsPreview="True"/>
            <TextBox Grid.Row="1" Grid.Column="2" BorderBrush="Black"/>
        </Grid>
    </Window>

    具体的GridSplitter的属性见http://www.cnblogs.com/luluping/archive/2011/08/26/2155218.html

    3.6 WrapPanel

      此控件会根据布局的大小来控制内容元素的排列。不会因为窗体没有放大,影响到其他内容的显示。在此只举一个例子,来理解WrapPanel。上代码了:

    XAML
    <Window x:Class="Chapter_03.WrapPanel"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="WrapPanel" Height="300" Width="300">
        <WrapPanel>
            <Button Width="50" Height="50"/>
            <Button Width="50" Height="50"/>
            <Button Width="50" Height="50"/>
            <Button Width="50" Height="50"/>
            <Button Width="50" Height="50"/>
            <Button Width="50" Height="50"/>
            <Button Width="50" Height="50"/>
        </WrapPanel>
    </Window>

    效果图如图10:

      图10

    四、总结

      布局一直是自己的弱项,所以可能这篇记录的会比较差点,但是重在理解控件的作用以及能举一反三。 虽然控件没有一一列出,但是对于每一族的控件都给出了一个实例,可以通过实例加深对各个控件的理解,具体的运用还需多加强练习和查阅msdn。下一篇:深入浅出话Binding。 

  • 相关阅读:
    Linux磁盘空间被未知资源耗尽
    磁盘的分区、格式化、挂载(转)
    sp_MSforeachtable和sp_MSforeachdb
    分布式缓存系统 Memcached 【转载】
    在性能计数的时候使用StopWatch类型
    数据库设计阶段中为何要考虑“反规范化”
    再谈谈数据库镜像之客户端重定向
    当SQL Server排序时遇上了NULL值
    ArrayList的动态扩展
    SSMS 2008的智能感知仅仅针对SQL Server 2008的数据库有效
  • 原文地址:https://www.cnblogs.com/lzhp/p/2669764.html
Copyright © 2011-2022 走看看