WPF C#Classes,TextBox和Reference,Easy(?)“在当前上下文中不存在”

时间:2009-10-01 12:45:26

标签: c# wpf

我把头发拉了出来。我创建了一个类“employee.cs”。我最初在“Window1.xaml.cs”的“公共部分类Window1:Window”中开发了这个类。当它移动到sepate类时,我不能再引用textBoxes,comboBoxes等。我该怎么办?给出的错误是“名称'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!
        }
    }
}

Class.cs

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

2 个答案:

答案 0 :(得分:2)

正如其他答案所暗示的那样,您需要在Window XAML中更改您的class属性。

    <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>

此更改应使您的文本框引用有效。

答案 1 :(得分:0)

xaml中的

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