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

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

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

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

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

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

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

在不知道您想要实现的目标的情况下,很难推荐正确的解决方案。

您之前看到的代码是针对Windows Forms的 ,您正在尝试使用WPF。 您可能想尝试

this.FindName(myName);

这是FrameworkElement.FindName方法,它将找到具有与之关联的x:Name内容。

使用:

this.FindName(myName);

如果您为控件分配了x:name ,则此方法有效。

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

暂无
暂无

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

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