简体   繁体   English

this.Control不起作用

[英]this.Control doesn't work

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);
        }
    }
}

The above code returns the following error: 上面的代码返回以下错误:

Error 1 'WpfTestApp.MainWindow' does not contain a definition for 'Controls' and no extension method 'Controls' accepting a first argument of type 'WpfTestApp.MainWindow' could be found (are you missing a using directive or an assembly reference?) 错误1'WpfTestApp.MainWindow'不包含'Controls'的定义,也没有扩展方法'Controls'接受类型为'WpfTestApp.MainWindow'的第一个参数(你是否缺少using指令或程序集引用?)

this. doesn't offer Controls as an option through intellisense. 不通过intellisense提供Controls作为选项。 But I've seen this.Contols.find(<name of control>) in code examples before. 但我之前在代码示例中看过this.Contols.find(<name of control>) But I can't seem to get it to work. 但我似乎无法让它发挥作用。

Any help would be appreciated, I'm using c# with Visual Studio 2010 任何帮助将不胜感激,我正在使用Visual Studio 2010的c#

Controls is a WinForms property, but you are using WPF. Controls是一个WinForms属性,但您使用的是WPF。

It's all completely different in WPF. 它在WPF中完全不同。 For example, the Window class does not support children which is why there is no Controls property. 例如, Window类不支持子级,这就是没有Controls属性的原因。

Without knowing what you are trying to achieve it's hard to recommend the right solution. 在不知道您想要实现的目标的情况下,很难推荐正确的解决方案。

The code you've seen before is for Windows Forms and you're trying to work with WPF. 您之前看到的代码是针对Windows Forms的 ,您正在尝试使用WPF。 You might want to try : 您可能想尝试

this.FindName(myName);

This is the FrameworkElement.FindName method and will find something that has an x:Name associatd with it. 这是FrameworkElement.FindName方法,它将找到具有与之关联的x:Name内容。

Use: 使用:

this.FindName(myName);

This will work if you have assigned an x:name to your control. 如果您为控件分配了x:name ,则此方法有效。

Check out this answer as this is a more robust solution. 看看这个答案,因为这是一个更强大的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM