6

说我添加了许多文本框。如何迭代或循环遍历所有文本框并进行一些检查。检查每个文本框的内容是否为数字。

下面是winForm的代码,在WinRT中怎么做?

foreach (Control item in GroupBox1.Controls)
{

    if (item.GetType() == typeof(TextBox))
    {
        if (string.IsNullOrEmpty( ((TextBox)item).Text))
        {
            //Empty text in this box
        }
    }
}

谢谢。

4

3 回答 3

3

这就是你做你想做的事的方式。

public MainPage()
{
    this.InitializeComponent();
    Loaded += MainPage_Loaded;
}

void MainPage_Loaded(object sender, RoutedEventArgs e)
{
    foreach (var textBox in AllTextBoxes(this))
    {
        textBox.Text = "Hello world";
    }
}

List<TextBox> AllTextBoxes(DependencyObject parent)
{
    var list = new List<TextBox>();
    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
    {
        var child = VisualTreeHelper.GetChild(parent, i);
        if (child is TextBox)
            list.Add(child as TextBox);
        list.AddRange(AllTextBoxes(child));
    }
    return list;
}

参考:http ://blog.jerrynixon.com/2012/09/how-to-access-named-control-inside-xaml.html

祝你好运!

于 2013-08-02T19:07:27.793 回答
1

你可以这样做。每个页面都会有一个容器UIElements,所以我使用的是Grid. 你也可以做同样的事情StackPanel。我正在遍历它的孩子并检查它是否Textbox存在。

XAML

<Grid x:Name="rootGrid" Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
    <TextBox Height="51" Margin="210,103,0,0" Text="TextBox" Width="135"/>
    <TextBox Height="51" Margin="459,149,0,0" Text="TextBox" Width="135"/>
    <TextBox Height="51" Margin="277,279,0,0" Text="TextBox" Width="135"/>
    <TextBox Height="51" Margin="580,279,0,0" Text="TextBox" Width="135"/>
    <TextBlock Height="63" Margin="227,494,0,0" Text="TextBlock" Width="142"/>
    <TextBlock Height="63" Margin="479,469,0,0" Text="TextBlock" Width="142"/>
    <TextBlock Height="63" Margin="573,406,0,0" Text="TextBlock" Width="142"/>
    <TextBlock Height="63" Margin="143,352,0,0" Text="TextBlock" Width="142"/>
    <CheckBox Content="CheckBox" Height="81" Margin="1064,203,0,0" Width="130"/>
    <CheckBox Content="CheckBox" Height="81" Margin="713,119,0,0" Width="130"/>
    <CheckBox Content="CheckBox" Height="81" Margin="831,352,0,0" Width="130"/>
</Grid>

C#

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    foreach (var child in rootGrid.Children)
    {
        if (child is TextBox)
        {
            System.Diagnostics.Debug.WriteLine(((TextBox)child).Text);
            if (string.IsNullOrEmpty(((TextBox)child).Text))
            {
                //Empty text in this box
            }
        }
    }
}
于 2013-08-02T05:03:30.370 回答
1

//如果你没有母版页,在asp.net c#中

    foreach (Control ctrl in Page.Controls)
    {
        if (ctrl is TextBox)
        {

            ((TextBox)ctrl).Text = string.Empty;
        }
    }

/如果你有母版页那么/

foreach (Page.Form.FindControl("ContentPlaceHolder1").Controls 中的控件项) { if (item is TextBox) { ((TextBox)item).Text = string.Empty; } }

于 2017-01-04T10:47:31.987 回答