尝试用一些简单的代码制作一个文本框,但不确定为什么会出错

Trying to make a textbox with a simple bit of code but not sure why it gives error

public partial class MainWindow : Window
{
    private Rectangle player = new Rectangle();
    private int x=0;
    private int y = 0;
    private System.Windows.Threading.DispatcherTimer timer = new System.Windows.Threading.DispatcherTimer();    

    public MainWindow()
    {
        InitializeComponent();
        player.Width = 50;
        player.Height = 50;
        player.Fill = Brushes.Red;
        player.MouseEnter += Player_MouseEnter;
        player.MouseLeave += Player_MouseLeave;
        player.MouseDown += Player_MouseDown;
        myCanvas.Children.Add(player);
    }

    private void Player_MouseDown(object sender, MouseButtonEventArgs e)
    {
        Random rand = new Random(); //Creates the pseudo-random movement
        int a = rand.Next(1, 1001); //With variables a and b
        int b = rand.Next(1, 1001);

        Canvas.SetLeft(player, a);
        Canvas.SetTop(player, b);
    }

    private void Player_MouseLeave(object sender, MouseEventArgs e)
    {
        player.Fill = Brushes.Red;
    }

    private void Player_MouseEnter(object sender, MouseEventArgs e)
    {
        player.Fill = Brushes.Blue;
    }

    public void drawPlayer()//makes it easier to redraw after every click
    {
        Canvas.SetLeft(player, x);
        Canvas.SetTop(player, y);
    }
    private void makeTextBox(//needs something here?)
    {
        TextBox.Text = "POINTS Counter";//Using this later on
    }

}

我猜这个文本框代码需要 makeTextBox() 中的一些东西才能有意义。但是我无法弄清楚我是wpf的新手,一般来说是c#。该代码只是创建了一个正方形,如果有人将鼠标悬停在其上,该正方形会改变颜色。然后它在 x 和 y 轴(1 到 1000 之间)上移动一个伪随机量。我现在想添加一个计时器和积分系统,但无法制作文本框。

我一直收到错误消息

CS0120 C# An object reference is required for the non-static field, method, or property 'TextBox.Text'

如果有人能提供帮助那就太好了!

您从未初始化您的文本框

对于任何面向对象的编程语言,您都不能直接访问 classes,除非它们是静态的。

TextBox 不是静态的 class。 我强烈建议按照评论中的建议在 xaml 中添加文本框。 如果您出于任何原因不想这样做,请写

TextBox MyTextbox = new TextBox();
MyTextBox.Text  = "POINTS Counter";//Using this later on

它应该可以工作。

编辑:但是,即使您的错误将消失,您也不会通过这样做看到您的文本框。

为了让它可见,你需要让你的容器对象知道它。我猜你在 xaml 代码中使用了某种网格,它可能看起来像这样:

<Window x:Class="Mytest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:pigc="http://schemas.proleit.com/ic/GUI/Charts"
    xmlns:pic="http://schemas.proleit.com/ic/Core"
    xmlns:local="clr-namespace:Stanlytest"
    xmlns:graph="clr-namespace:Graph"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800">
<Grid>
<!- Whatever you do here -->

</Grid>

现在给您的网格命名,如果您还没有(例如 <Grid Name="MainGrid"> </Grid>),然后将文本框作为子项添加到 xaml.cs 中的网格(例如:MainGrid.Children.Add(MyTextBox).)

我再次提醒你,虽然这对新手来说一开始有点陌生(我自己最近才开始学习wpf),但你应该在xaml.

中添加你的对象