立即清除多个TextBox中的文本

时间:2011-07-21 22:19:43

标签: c# wpf

我有一个Grid的WPF应用程序,其中有多个TextBox。如何通过点击按钮来制作每个TextBox.Text = null;

4 个答案:

答案 0 :(得分:4)

尝试一下:

   private void button1_Click(object sender, RoutedEventArgs e)
    {
        foreach (UIElement control in myGrid.Children)
        {
            if (control.GetType() == typeof(TextBox))
            {
                TextBox txtBox = (TextBox)control;
                txtBox.Text = null;
            }
        }
    }

答案 1 :(得分:3)

这样的事情会起作用:

private void Button_Click(object sender, RoutedEventArgs e) {
    foreach (UIElement element in this.grid.Children) {
        TextBox textBox = element as TextBox;
        if (textBox == null)
            continue;

        textBox.Text = null;
    }
}

答案 2 :(得分:1)

Tom和CodeNaked提供的代码将按照您的意愿执行,但我通常建议不要使用此逻辑。

网格可以帮助您组织控件直观,它是布局容器。绝不应该用它来在幕后组织你的控件逻辑

正如我所说,这是非常普遍的建议。您的计划可能会从另一种方法中受益。

答案 3 :(得分:1)

这个问题有多种方法。

第一种是混合方法,您可以通过绑定将数据流向文本框,然后单击按钮删除数据。

首先,您需要确保您的数据类实现INotifyPropertyChanged

public class Foo : INotifyPropertyChanged
{
    private string bar;
    private string baz;

    public string Bar
    {
        get { return this.bar; }
        set
        {
            this.bar = value;

            // this is where the magic of bindings happens
            this.OnPropertyChanged("Bar");
        }
    }

    // rest of the class here...
}

通过绑定在您的XAML中引用:

<Grid>
    <Grid.RowDefinitions>
        <!-- ... -->
    </Grid.RowDefinitions>
    <TextBox Grid.Row="0"
             Text="{Binding Bar}" />
    <TextBox Grid.Row="1"
             Text="{Binding Baz}" />

    <!-- A more complete example would use Button.Command -->
    <Button Grid.Row="2"
            Content="CLEAR"
            Click="ClearButton_Click" />

最后,使用DataContextWindow代码隐藏中的路由事件处理程序连接这些绑定:

public Window1()
{
    this.InitializeComponent();

    // sets up the DataContext used by the bindings
    this.Clear();
}

private void ClearButton_Click(object sender, RoutedEventArgs e)
{
    this.Clear();
}

private void Clear()
{
    this.DataContext = new Foo();
}

这种方法可以帮助您更好地处理更复杂的UI。


最后的努力将是:

/// <summary>This is a bad choice.</summary>
private void ClearButton_Click(object sender, RoutedEventArgs e)
{
    // assumes the Grid is named MyGrid
    foreach (var textBox in this.MyGrid.Children.OfType<TextBox>())
    {
        textBox.Text = null;
    }
}
相关问题