WPF--Grid布局
后台部分代码:
public void CalculateYourLife() { Title = "Calculate your life "; SizeToContent = SizeToContent.WidthAndHeight; ResizeMode = ResizeMode.CanMinimize;//设置窗口类型 Grid grid = new Grid();//声明网格布局 Content = grid; for (int i = 0; i < 3; i++) { RowDefinition rowdef = new RowDefinition();//创建三行,行高为自动调整 rowdef.Height = GridLength.Auto; grid.RowDefinitions.Add(rowdef);//将三行添加到网格上 } for (int i = 0; i < 2; i++) { ColumnDefinition coldef = new ColumnDefinition();//创建二列,列宽为自动调整 coldef.Width = GridLength.Auto; grid.ColumnDefinitions.Add(coldef);//将两列添加到风格上 } //创建label 将其放置到第一行第一列中 Label lbl = new Label(); lbl.Content = "beging date:"; grid.Children.Add(lbl); Grid.SetRow(lbl, 0); Grid.SetColumn(lbl, 0); //创建textbox放置到第一行第二列中,并添加一个事件处理 txtbegin.Text = new DateTime(1980, 1, 1).ToShortDateString(); txtbegin.TextChanged += TextBoxOnTextChange; grid.Children.Add(txtbegin); Grid.SetRow(txtbegin, 0); Grid.SetColumn(txtbegin, 1); //创建label将其放置到第二行的第一列中 Label lblT = new Label(); lblT.Content = "end date:"; grid.Children.Add(lblT); Grid.SetRow(lblT, 1); Grid.SetColumn(lblT,0); //创建textbox放置到第二行第二列中,并添加一个事件处理 txtEnd.TextChanged += TextBoxOnTextChange; grid.Children.Add(txtEnd); Grid.SetRow(txtEnd, 1); Grid.SetColumn(txtEnd, 1); 创建label将其放置到第三行的第一列中 Label lblTh = new Label(); lblTh.Content = "life years:"; grid.Children.Add(lblTh); Grid.SetRow(lblTh, 2); Grid.SetColumn(lblTh, 0); grid.Children.Add(lbllifeyears); Grid.SetRow(lbllifeyears, 2); Grid.SetColumn(lbllifeyears, 1); Thickness thick = new Thickness(5); grid.Margin = thick; txtbegin.Focus(); txtEnd.Text = DateTime.Now.ToShortDateString(); } //事件 void TextBoxOnTextChange(object Sender, TextChangedEventArgs e) { DateTime dtbegin, dtend; if (DateTime.TryParse(txtbegin.Text,out dtbegin) && DateTime.TryParse(txtEnd.Text, out dtend))//对比两个时间是否相同 { int iYear = dtend.Year - dtbegin.Year;//获得年 int iMonths = dtend.Month - dtbegin.Month;//获得月 int iDays = dtend.Day - dtbegin.Day;//获得天 if (iDays < 0) { iDays += DateTime.DaysInMonth(dtend.Year, 1 + (dtend.Month + 10) % 12);//返回指定年和月中的天数 iMonths -= 1; } if (iMonths < 0) { iMonths += 12; iYear -= 1; } //格式化显示数据 lbllifeyears.Content = String.Format("{0} year{1},{2} month{3}, {4} day{5}", iYear, iYear == 1 ? "" : "s",iMonths, iMonths == 1 ? "" : "s",iDays, iDays == 1 ? "" : "s"); } else { lbllifeyears.Content = ""; } }
本文只作为学习用,若有不对之处请高人明示!