本文介绍了清除C#中的文本框问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法正确运行此代码。它说对象引用未设置为对象的实例。我在C Sharp中使用WPF格式。谢谢。



我的尝试:



private void btnClear_Click(对象发送者,RoutedEventArgs e)

{

foreach(this.Controls中的控制控件)

{

if (控件是TextBox)

{

TextBox textBox =控制为TextBox;

textBox.Clear();

}

}





}

I cannot run this code correctly. It says "Object reference not set to an instance of an object." I am using WPF format in C Sharp. Thanks.

What I have tried:

private void btnClear_Click(object sender, RoutedEventArgs e)
{
foreach (Control control in this.Controls)
{
if (control is TextBox)
{
TextBox textBox = control as TextBox;
textBox.Clear();
}
}


}

推荐答案

private void Button_Click(object sender, RoutedEventArgs e)
{
    ClearTextBoxes(this);
}

private void ClearTextBoxes(DependencyObject parentDependencyObject)
{
    int visualChildrenCount = VisualTreeHelper.GetChildrenCount(parentDependencyObject);
    for (int i = 0; i < visualChildrenCount; i++)
    {
        // Retrieve child visual 
        DependencyObject dependencyObject = VisualTreeHelper.GetChild(parentDependencyObject, i);

        TextBox textBox = dependencyObject as TextBox;
        if (textBox != null)
        {
            textBox.Clear();
        }
        else
        {
            ClearTextBoxes(dependencyObject);
        }
    }
}



但我建议你去寻找一个更通用的解决方案,如下所述:

[]

我希望它有所帮助。


But I would suggest you to go for a more general solution like described here:
c# - Find all controls in WPF Window by type - Stack Overflow[^]
I hope it helps.




这篇关于清除C#中的文本框问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 22:52
查看更多