《WPF程序设计指南》读书笔记——第6章 Dock与Grid
1.DockPanel面板
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; namespace LY.DockAroundTheBlock { class DockAroundTheBlock:Window { [STAThread] public static void Main() { new Application().Run(new DockAroundTheBlock()); } public DockAroundTheBlock() { Title = "Dock Around The Block"; DockPanel dock = new DockPanel(); //LastChildFill属性默认值为true //dock.LastChildFill = false; Content = dock; for (int i = 0; i < 17; i++) { Button btn = new Button(); btn.Content = "Button No. " + (i + 1); dock.Children.Add(btn); //将数值直接转换为枚举 //以下两种方法都可以 //btn.SetValue(DockPanel.DockProperty, (Dock)(i % 4)); DockPanel.SetDock(btn, (Dock)(i % 4)); } } } }
2.Grid面板
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; namespace LY.CalculateYourLife { class CalculateYourLife : Window { TextBox txtboxBegin, txtboxEnd; Label lblLifeYears; [STAThread] public static void Main() { Application app = new Application(); app.Run(new CalculateYourLife()); } public CalculateYourLife() { Title = "Calculate Your Life"; SizeToContent = SizeToContent.WidthAndHeight; ResizeMode = ResizeMode.CanMinimize; Grid grid = new Grid(); Content = grid; //显示Grid面板的网格线 grid.ShowGridLines = true; // 行和列的定义 for (int i = 0; i < 3; i++) { //RowDefinitions是RowDefinition的集合 //用于定义网格的行 RowDefinition rowdef = new RowDefinition(); /* * GridLength是结构体,可以用GridLength.Auto静态属性定义行的高度,如果 *用GridLength.Pixel(固定大小)或GridLength.Star(可用空间百分比)枚举 *也可以用new GridLength()构造函数,来指定固定大小或分配权重 *如果在new GridLength()构造函数中用GridLength.Auto枚举,则会忽略数值 */ rowdef.Height = GridLength.Auto;//根据内容自动设定高度 //rowdef.Height = new GridLength(100, GridUnitType.Pixel); //Grid会将所有GridUnitType.Star枚举值加起来得到总和,然后 //让每个值除以总和,以决定空间分配比 //rowdef.Height = new GridLength(20, GridUnitType.Star); //如果用无参数构造函数,则默认为GridUnitType.Star,权重值为1 //rowdef.Height = new GridLength(); grid.RowDefinitions.Add(rowdef); } for (int i = 0; i < 2; i++) { ColumnDefinition coldef = new ColumnDefinition(); coldef.Width = GridLength.Auto; grid.ColumnDefinitions.Add(coldef); } // First label. Label lbl = new Label(); lbl.Content = "Begin Date: "; grid.Children.Add(lbl); //将控件放到Grid面板中 Grid.SetRow(lbl, 0); Grid.SetColumn(lbl, 0); // First TextBox. txtboxBegin = new TextBox(); txtboxBegin.Text = new DateTime(1980, 1, 1).ToShortDateString(); txtboxBegin.TextChanged += TextBoxOnTextChanged; grid.Children.Add(txtboxBegin); Grid.SetRow(txtboxBegin, 0); Grid.SetColumn(txtboxBegin, 1); // Second label. lbl = new Label(); lbl.Content = "End Date: "; grid.Children.Add(lbl); Grid.SetRow(lbl, 1); Grid.SetColumn(lbl, 0); // Second TextBox. txtboxEnd = new TextBox(); txtboxEnd.TextChanged += TextBoxOnTextChanged; grid.Children.Add(txtboxEnd); Grid.SetRow(txtboxEnd, 1); Grid.SetColumn(txtboxEnd, 1); // Third label. lbl = new Label(); lbl.Content = "Life Years: "; grid.Children.Add(lbl); Grid.SetRow(lbl, 2); Grid.SetColumn(lbl, 0); // Label for calculated result. lblLifeYears = new Label(); grid.Children.Add(lblLifeYears); Grid.SetRow(lblLifeYears, 2); Grid.SetColumn(lblLifeYears, 1); // Set margin for everybody. Thickness thick = new Thickness(5); grid.Margin = thick; //遍历控件 foreach (Control ctrl in grid.Children) ctrl.Margin = thick; txtboxBegin.Focus(); txtboxEnd.Text = DateTime.Now.ToShortDateString(); } void TextBoxOnTextChanged(object sender, TextChangedEventArgs args) { DateTime dtBeg, dtEnd; if (DateTime.TryParse(txtboxBegin.Text, out dtBeg) && DateTime.TryParse(txtboxEnd.Text, out dtEnd)) { int iYears = dtEnd.Year - dtBeg.Year; int iMonths = dtEnd.Month - dtBeg.Month; int iDays = dtEnd.Day - dtBeg.Day; if (iDays < 0) { iDays += DateTime.DaysInMonth(dtEnd.Year, 1 + (dtEnd.Month + 10) % 12); iMonths -= 1; } if (iMonths < 0) { iMonths += 12; iYears -= 1; } lblLifeYears.Content = String.Format("{0} year{1}, {2} month{3}, {4} day{5}", iYears, iYears == 1 ? "" : "s", iMonths, iMonths == 1 ? "" : "s", iDays, iDays == 1 ? "" : "s"); } else { lblLifeYears.Content = ""; } } } }
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; namespace LY.EnterTheGrid { public class EnterTheGrid : Window { [STAThread] public static void Main() { Application app = new Application(); app.Run(new EnterTheGrid()); } public EnterTheGrid() { Title = "Enter the Grid"; MinWidth = 300; SizeToContent = SizeToContent.WidthAndHeight; //新建一个StackPanel StackPanel stack = new StackPanel(); Content = stack; //新建Grid面板,并且加入到StackPanel Grid grid1 = new Grid(); grid1.Margin = new Thickness(5); stack.Children.Add(grid1); //设定行 for (int i = 0; i < 5; i++) { RowDefinition rowdef = new RowDefinition(); rowdef.Height = GridLength.Auto; grid1.RowDefinitions.Add(rowdef); } //设定列 ColumnDefinition coldef = new ColumnDefinition(); coldef.Width = GridLength.Auto; grid1.ColumnDefinitions.Add(coldef); coldef = new ColumnDefinition(); //第二列会随着边框拉大而自动变大,因为其GridUnitType为Star coldef.Width = new GridLength(100, GridUnitType.Star); grid1.ColumnDefinitions.Add(coldef); //创建labels控件 string[] strLabels = { "_First name:", "_Last name:", "_Social security number:", "_Credit card number:", "_Other personal stuff:" }; for(int i = 0; i < strLabels.Length; i++) { Label lbl = new Label(); lbl.Content = strLabels[i]; lbl.VerticalContentAlignment = VerticalAlignment.Center; grid1.Children.Add(lbl); Grid.SetRow(lbl, i); Grid.SetColumn(lbl, 0); TextBox txtbox = new TextBox(); txtbox.Margin = new Thickness(5); grid1.Children.Add(txtbox); Grid.SetRow(txtbox, i); Grid.SetColumn(txtbox, 1); } //再新建一个Grid面板,并且加入到StackPanel Grid grid2 = new Grid(); grid2.Margin = new Thickness(10); stack.Children.Add(grid2); // 因为grid2只需要有一行,因此不用定义行 // 默认方式下是Star枚举,权重值为1 grid2.ColumnDefinitions.Add(new ColumnDefinition()); grid2.ColumnDefinitions.Add(new ColumnDefinition()); grid2.ColumnDefinitions.Add(new ColumnDefinition()); grid2.ShowGridLines = true; //加入按钮 Button btn = new Button(); btn.Content = "Submit"; btn.HorizontalAlignment = HorizontalAlignment.Center; btn.IsDefault = true; btn.Click += delegate { Close(); }; grid2.Children.Add(btn); // 默认情况下行和列都是0 Grid.SetColumnSpan(btn, 2); // 跨两个列 btn = new Button(); btn.Content = "Cancel"; btn.HorizontalAlignment = HorizontalAlignment.Center; btn.IsCancel = true; btn.Click += delegate { Close(); }; grid2.Children.Add(btn); Grid.SetColumn(btn, 2); //默认行是0. //设定激活控件 (stack.Children[0] as Panel).Children[1].Focus(); } } }
3.GridSplitter控件(只能在Grid面板中使用)
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Media; namespace LY.SplitNine { class SplitNine:Window { [STAThread] public static void Main() { new Application().Run(new SplitNine()); } public SplitNine() { Title = "Split Nine"; Grid grid = new Grid(); grid.ShowGridLines = true; Content = grid; for (int i = 0; i < 3; i++) { grid.RowDefinitions.Add(new RowDefinition()); grid.ColumnDefinitions.Add(new ColumnDefinition()); } for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { Button btn = new Button(); btn.Content = "行" + j + "列" + i; btn.Margin = new Thickness(5); grid.Children.Add(btn); //Grid类静态方法设定控件在Grid面板上位置 Grid.SetRow(btn, j); Grid.SetColumn(btn, i); } } GridSplitter split = new GridSplitter(); //是否同时显示拖动前的split控件位置 split.ShowsPreview = true; //split默认在网格cell中靠右伸展 //水平分隔控件 split.HorizontalAlignment = HorizontalAlignment.Stretch; split.VerticalAlignment = VerticalAlignment.Top; //垂直分隔控件 //split.HorizontalAlignment = HorizontalAlignment.Center; //split.VerticalAlignment = VerticalAlignment.Stretch; //拖动split会影响到哪些行和列 split.ResizeBehavior = GridResizeBehavior.CurrentAndNext; //拖动split会影响到行还是列 split.ResizeDirection = GridResizeDirection.Rows; //split默认宽度和高度为0,所以必须设一个值 //注意:水平分隔时,不能只设width(Stretch属性设定了)不设Heigth //注意:垂直分隔时,不能只设Heigth(Stretch属性设定了)不设width //注意:否则分割线没有Heigth或width都会显示不出来 split.Width = 30; split.Height = 20; split.Background = Brushes.Red; split.Margin = new Thickness(10); grid.Children.Add(split); Grid.SetRow(split, 1); Grid.SetColumn(split, 1); //Grid.SetRowSpan(split,3); } } }
4.ScrollBar控件
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Media; class ColorScroll : Window { ScrollBar[] scrolls = new ScrollBar[3]; TextBlock[] txtValue = new TextBlock[3]; Panel pnlColor; [STAThread] public static void Main() { Application app = new Application(); app.Run(new ColorScroll()); } public ColorScroll() { Title = "Color Scroll"; Width = 500; Height = 300; // GridMain contains a vertical splitter. Grid gridMain = new Grid(); Content = gridMain; // GridMain column definitions. ColumnDefinition coldef = new ColumnDefinition(); coldef.Width = new GridLength(200, GridUnitType.Pixel); gridMain.ColumnDefinitions.Add(coldef); coldef = new ColumnDefinition(); coldef.Width = GridLength.Auto; gridMain.ColumnDefinitions.Add(coldef); coldef = new ColumnDefinition(); coldef.Width = new GridLength(100, GridUnitType.Star); gridMain.ColumnDefinitions.Add(coldef); // Vertical splitter. GridSplitter split = new GridSplitter(); split.HorizontalAlignment = HorizontalAlignment.Center; split.VerticalAlignment = VerticalAlignment.Stretch; split.Width = 6; gridMain.Children.Add(split); Grid.SetRow(split, 0); Grid.SetColumn(split, 1); // Panel on right side of splitter to display color pnlColor = new StackPanel(); pnlColor.Background = new SolidColorBrush(SystemColors.WindowColor); gridMain.Children.Add(pnlColor); Grid.SetRow(pnlColor, 0); Grid.SetColumn(pnlColor, 2); // Secondary grid at left of splitter Grid grid = new Grid(); gridMain.Children.Add(grid); Grid.SetRow(grid, 0); Grid.SetColumn(grid, 0); // Three rows for label, scroll, and label. RowDefinition rowdef = new RowDefinition(); rowdef.Height = GridLength.Auto; grid.RowDefinitions.Add(rowdef); rowdef = new RowDefinition(); rowdef.Height = new GridLength(100, GridUnitType.Star); grid.RowDefinitions.Add(rowdef); rowdef = new RowDefinition(); rowdef.Height = GridLength.Auto; grid.RowDefinitions.Add(rowdef); // Three columns for Red, Green, and Blue. for (int i = 0; i < 3; i++) { coldef = new ColumnDefinition(); coldef.Width = new GridLength(33, GridUnitType.Star); grid.ColumnDefinitions.Add(coldef); } for (int i = 0; i < 3; i++) { Label lbl = new Label(); lbl.Content = new string[] { "Red", "Green", "Blue" }[i]; lbl.HorizontalAlignment = HorizontalAlignment.Center; grid.Children.Add(lbl); Grid.SetRow(lbl, 0); Grid.SetColumn(lbl, i); scrolls[i] = new ScrollBar(); scrolls[i].Focusable = true; scrolls[i].Orientation = Orientation.Vertical; scrolls[i].Minimum = 0; scrolls[i].Maximum = 255; scrolls[i].SmallChange = 1; scrolls[i].LargeChange = 16; scrolls[i].ValueChanged += ScrollOnValueChanged; grid.Children.Add(scrolls[i]); Grid.SetRow(scrolls[i], 1); Grid.SetColumn(scrolls[i], i); txtValue[i] = new TextBlock(); txtValue[i].TextAlignment = TextAlignment.Center; txtValue[i].HorizontalAlignment = HorizontalAlignment.Center; txtValue[i].Margin = new Thickness(5); grid.Children.Add(txtValue[i]); Grid.SetRow(txtValue[i], 2); Grid.SetColumn(txtValue[i], i); } // Initialize scroll bars. Color clr = (pnlColor.Background as SolidColorBrush).Color; scrolls[0].Value = clr.R; scrolls[1].Value = clr.G; scrolls[2].Value = clr.B; // Set initial focus. scrolls[0].Focus(); } void ScrollOnValueChanged(object sender, RoutedEventArgs args) { ScrollBar scroll = sender as ScrollBar; Panel pnl = scroll.Parent as Panel; TextBlock txt = pnl.Children[1 + pnl.Children.IndexOf(scroll)] as TextBlock; txt.Text = String.Format("{0}\n0x{0:X2}", (int)scroll.Value); pnlColor.Background = new SolidColorBrush( Color.FromRgb((byte) scrolls[0].Value, (byte) scrolls[1].Value,(byte) scrolls[2].Value)); } }