【问题标题】:WPF C# Classes, TextBox and Reference, Easy(?) "does not exist in the current context"WPF C# 类、TextBox 和引用、Easy(?)“当前上下文中不存在”
【发布时间】:2009-10-01 12:45:26
【问题描述】:

我正在拔头发。我创建了一个类“employee.cs”。我最初在“Window1.xaml.cs”上的“公共部分类 Window1:Window”中开发了这个类。将它移动到单独的类时,我不能再引用文本框、组合框等。我该怎么办?给出的错误是“当前上下文中不存在名称‘textBox1’”。我敢肯定它很简单!谢谢各位!

这是一个缩减的例子!

Window1.xaml

<Window x:Class="WpfApplication6.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
  <Grid>
    <TextBox Height="100" Margin="12,12,23,0" Name="textBox1" VerticalAlignment="Top" />
  </Grid>
</Window>

Window1.xaml.cs

namespace WpfApplication6
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
            textBox1.Text = "testing"; //Works Here!
        }
    }
}

类.cs

namespace WpfApplication6
{
    class class1
    {
        public static void main()
        {
            textBox1.Text = "Help"; //Doesn't Work Here!! :-(
        }
    }
}

【问题讨论】:

  • 请问您到底想做什么?也许我们可以提出一个替代解决方案。

标签: c# wpf


【解决方案1】:

正如这里的另一个答案所暗示的,您将需要在 Window XAML 中更改您的类属性。

    <Window x:Class="WpfApplication6.class1"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      Title="Window1" Height="300" Width="300">  
      <Grid>    
         <TextBox Height="100" Margin="12,12,23,0" 
                  Name="textBox1" VerticalAlignment="Top" />  
      </Grid>
    </Window>

此更改应该使您的文本框引用工作。

【讨论】:

    【解决方案2】:

    x:Class="WpfApplication6.Window1 在 xaml 告诉你这是 Window1 类的一部分。窗口(来自 xaml)将成为该类的部分成员。

    【讨论】:

    • 感谢您的回答。那么是否可以在 xaml 中声明多个类?或者我追求的另一种方式?谢谢。
    • @Dan -- 将 XAML 视为获取常规 CLR 类、实例化它们、设置它们的属性并将它们组合在一起的简写符号。在顶层,您可以定义自己的包含所有这些的类(通过InitialiseComponent)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-16
    • 1970-01-01
    • 1970-01-01
    • 2018-03-21
    • 1970-01-01
    • 2014-12-06
    • 1970-01-01
    相关资源
    最近更新 更多