【问题标题】:C# WPF - Add to a list in another classC# WPF - 添加到另一个类中的列表
【发布时间】:2020-04-06 08:52:36
【问题描述】:

我是 C# 和 WPF 的初学者。我正在创建一个 PIN 系统,其中您有数字 0-9。用户单击一个按钮,例如 1,它会将 1 添加到列表中。作为这种编程语言和结构的初学者。我该怎么做呢,这是我到目前为止所拥有的,目前似乎没有任何效果。

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    public class MyVariables
    {
        public static List<int> pinNumbers = new List<int>();
    }

    private void PIN_0_Click(object sender, RoutedEventArgs e)
    {
        MyVariables.pinNumbers.Add(0);
        MessageBox.Show("List = " + MyVariables.pinNumbers);
    }

    private void PIN_1_Click(object sender, RoutedEventArgs e)
    {
        MyVariables.pinNumbers.Add(1);
    }
}

有简单的按钮,您单击一个,它应该添加到列表“pinNumbers”,但它似乎没有添加。谢谢,任何帮助都将不胜感激!

一些 XAML

<Grid>
   <Button x:Name="PIN_0" Content="0" Click="PIN_0_Click"></Button>
</Grid>

【问题讨论】:

  • “它似乎没有添加” -- 你的意思是什么?如果您正确设置了这些事件处理程序,则代码确实应该添加到列表中。您如何检查它们是否已被添加?
  • 我尝试过使用“MessageBox.Show("List = " + MyVariables.pinNumbers) 并使用 foreach 循环 "foreach (object o in MyVariables.pinNumbers) Console.WriteLine (o);"
  • 您需要包含一个minimal reproducible example,其中显示了一些 XAML 以及您用于显示列表内容的代码。您现在拥有的部分看起来还不错。还包括您从MessageBox 和/或Console.WriteLine 获得的输出
  • 感谢您的快速回复,我已经设法解决了。在 XAML 中,只有 Pin_0 具有单击事件,而所有其他按钮都没有。感谢您的帮助,我犯了一个简单的错误,现在可以正常工作了!!非常感谢赫罗塔!!

标签: c# wpf list append add


【解决方案1】:

您需要在变量中启动类并删除静态声明

public partial class MainWindow : Window
{
   private _myVariables { get; set; }
   public MainWindow()
   {
      InitializeComponent();
      _myVariables = new MyVariables()
   }

   public class MyVariables
   {
      public List<int> pinNumbers = new List<int>();
   }

   private void PIN_0_Click(object sender, RoutedEventArgs e)
   {
      _myVariables.pinNumbers.Add(0);
      MessageBox.Show("List = " + _myVariables.pinNumbers);
   }

   private void PIN_1_Click(object sender, RoutedEventArgs e)
   {
      _myVariables.pinNumbers.Add(1);
   }
}

【讨论】:

  • 感谢您的帖子和您的时间。我犯了一个简单的错误,现在我已经解决了。谢谢
猜你喜欢
  • 1970-01-01
  • 2012-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-18
  • 1970-01-01
相关资源
最近更新 更多