简体   繁体   中英

C# WPF - Add to a list in another class

I am a beginner in C# and WPF. I am creating a PIN system where you have digits 0-9. The user clicks a button for instance 1, and it will add 1 to a list. Being a beginner to this programming language and structure. How would I go about doing so, this is what I have so far and nothing seems to work at the moment.

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

There are simply buttons, you click one and it should add to the list "pinNumbers" but it doesn't seem to be adding. Thank you, any help with be appreciated!

Some XAML

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

you need to start the class in a variable and remove the static declaration

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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