现在的位置: 首页 > 综合 > 正文

容器StackPanel

2013年10月01日 ⁄ 综合 ⁄ 共 1851字 ⁄ 字号 评论关闭

写在前面:如果你一直在留意小作坊网之前介绍的WPF知识,你一定会好郁闷,因为介绍的Window,Button,Label等等,都只能设置Content,而Content只能设置为一个对象,不能够设置为多个控件,这样,在Window界面中,只能放一个控件,显然,这对于Window来说是不可以接受的。解决这个问题的方法是将Window的Content设置为一个容器Panel,而Panel只是一个虚类,它的派生类有Canvas,DockPanel,Grid,StackPanel,UniformGrid,WrapPanel。下面对StackPanel进行介绍。

效果图
下面的效果图,是在WinForm中很容易做出来的,而在WPF中,如果你不是很熟悉,可要浪费很多时间的。StackPanel的上半部分是一个StackPanel而下半部分是一个RichTextBox,StackPanel有一个Children的属性,它是一个UIElementCollection类型,一看到Collection,相信大家都很安心了,终于可以放多个控件了。
 

源代码
StackPanel可以使用Margin,它是一个Thickness类型,可以在初始化时设置,也可以初始化之后将Top,Left,Bottom,Right设置。而Children是一个集合类型,可以使用Add方法增加子控件,如Button,TextBox等都可以Add进去。Orientation属性是指一个布局方式,可以设置为水平Horizontal和垂直Vertical。

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Controls.Primitives;

namespace WPF
{
    public class WPFStackPanel:Window
    {
      
        [STAThread]
        public static void Main()
        {
            Application _application = new Application();
            _application.Run(new WPFStackPanel());
        }
        /// 
        /// 测试StackPanel容器
        /// 
        public WPFStackPanel()
        {            
            Title = "测试StackPanel容器";
            Width = 96 * 4;
            Height = 96 * 4;

            StackPanel _panel = new StackPanel();

            _panel.Background = Brushes.Pink;

            //上半部分的StackPanel
            StackPanel _panelTop = new StackPanel();            
            AddSubControl(_panelTop);
            _panelTop.Margin = new Thickness(10, 10, 10, 0);

            //下半部分的RichTextBox
            RichTextBox _richTextBox = new RichTextBox();
            _richTextBox.Margin = new Thickness(10,5,10,0);
            _richTextBox.Width = this.Width - 40;
            _richTextBox.Height = this.Height -100;

            _panel.Children.Add(_panelTop);
            _panel.Children.Add(_richTextBox);

            Content = _panel;            
        }

        private void AddSubControl(StackPanel _panel)
        {
            //水平布局
            _panel.Orientation = Orientation.Horizontal;    
            for (int i = 0; i < 5; i++)
            {
                Button _button = new Button();
                _button.Content = "按钮" + i;
                _button.Background = Brushes.PaleGreen;
                if (i % 2 == 1)
                {
                    TextBox _textBox = new TextBox();
                    _textBox.Text = "文本输入框" + i;
                    _textBox.AcceptsReturn = true;
                    _panel.Children.Add(_textBox);
                }
                _panel.Children.Add(_button);
            }
        }
    }
}

抱歉!评论已关闭.