WPF简单的口算案例

时间:2023-03-08 17:21:58

前几天在博客园,看到有博友利用Winform做了一个口算案例,于是我想把它移植在WPF程序中。Winform程序:http://www.cnblogs.com/ImYZF/p/3345452.html

WPF简单的口算案例

WPF中:

WPF简单的口算案例

个人感觉在WPF中动态创建完控件之后,无法有像Winform中FindName()这样的方法来对控件进行搜寻,因此我采用的方法是在布局控件中动态创建控件后,用for循环遍历布局中的控件,然后利用

布局控件的Children属性进行对控件的定位。

上代码:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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 口算训练
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
} private void btnAdd_Click(object sender, RoutedEventArgs e)
{
if (txtNum.Text == "")
{
MessageBox.Show("请输入数目!");
return;
}
//清空布局控件中的控件
grid2.Children.Clear();
int totalNumber = int.Parse(txtNum.Text);
Random random = new Random();
TextBox tb = new TextBox();
Label l = new Label();
for (int i = ; i < totalNumber; i++)
{
//根据问题的数量设置row的个数
grid2.RowDefinitions.Add(new RowDefinition() { Height=new GridLength()});
for (int j = ; j <=; j++)
{
//设置文本框的一些属性
tb = new TextBox();
tb.Width = ;
tb.Height = ;
tb.Name = "txt" + Convert.ToString(i)+Convert.ToString(j);
//附加属性
tb.SetValue(Grid.RowProperty, i);
tb.SetValue(Grid.ColumnProperty,(j-)*); if (j <= )
{
//产生随机数,作为加数
tb.Text = Convert.ToString(random.Next());
tb.IsReadOnly = true;
}
//添加子控件
grid2.Children.Add(tb);
l = new Label(); //创建Label
switch (j) {
case : l.Width = ; l.Height = ; l.Content = "+"; l.SetValue(Grid.RowProperty, i); l.SetValue(Grid.ColumnProperty, j);
break;
case : l.Width = ; l.Height = ; l.Content = "="; l.SetValue(Grid.RowProperty, i); l.SetValue(Grid.ColumnProperty, j + );
break;
case : l.Width = ; l.Height = ; ; l.Name = "labelresult" + Convert.ToString(i); ; l.SetValue(Grid.RowProperty, i); l.SetValue(Grid.ColumnProperty, j + );
break; }
grid2.Children.Add(l); } }
} private void btnResult_Click(object sender, RoutedEventArgs e)
{
int totalNumber=int.Parse(txtNum.Text);
TextBox[] tbs;
for (int i = ; i <=totalNumber; i++)
{ tbs = new TextBox[];
//获取有关TextBox控件
tbs[] = grid2.Children[ * (i-)] as TextBox;
tbs[] = grid2.Children[ * (i-) + ] as TextBox;
tbs[] = grid2.Children[ * (i-) + ] as TextBox; Label labelresult = grid2.Children[ * (i-) + ] as Label;
//如果未填答案,按错误处理
if (tbs[].Text == "")
{
labelresult.Content = "X";
continue;
}
int add = Convert.ToInt32(tbs[].Text) + Convert.ToInt32(tbs[].Text);
if (add == Convert.ToInt32(tbs[].Text))
{
labelresult.Content = "right!";
}
else
{
labelresult.Content = "X";
}
}
}
}
}