this.Control不起作用

时间:2011-04-19 12:38:19

标签: c# visual-studio-2010

using System.Text;
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;
using System.Windows.Forms;

namespace WpfTestApp
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            string myName;
            myName = "textBox1";
            this.Controls.Find(myName);
        }
    }
}

上面的代码返回以下错误:

  

错误1'WpfTestApp.MainWindow'不包含'Controls'的定义,也没有扩展方法'Controls'接受类型为'WpfTestApp.MainWindow'的第一个参数(你是否缺少using指令或程序集)引用?)

this.不会通过intellisense提供Controls作为选项。但我之前在代码示例中看过this.Contols.find(<name of control>)。但我似乎无法让它发挥作用。

任何帮助都将不胜感激,我正在使用Visual Studio 2010中的c#

3 个答案:

答案 0 :(得分:3)

Controls是WinForms属性,但您使用的是WPF。

在WPF中完全不同。例如,Window类不支持子级,这就是没有Controls属性的原因。

如果不知道你想要达到什么目标,很难推荐正确的解决方案。

答案 1 :(得分:2)

您之前看过的代码是Windows Forms,而您正在尝试使用WPF。您可能想要尝试

this.FindName(myName);

这是FrameworkElement.FindName方法,会找到与x:Name关联的内容。

答案 2 :(得分:1)

使用:

this.FindName(myName);

如果您为控件分配了x:name,则此功能将起作用。

查看此answer,因为这是一个更强大的解决方案。