Попытка понять C #, WPF и пользовательский ввод между функциями - PullRequest
0 голосов
/ 05 марта 2019

Я новичок здесь, а также C #.Я пытаюсь изучить его лучше и, как основная задача программирования для себя, я пытаюсь понять, как перемещать или возвращать определенные значения из пользовательских полей ввода / ввода текста после отправки в таблицу, отображаемую в списке.

Вот мой «вызов». Я пытаюсь создать простую программу, в которой есть 2 текстовых поля, одно для имени нового значения в списке (а не для массива, который я выучил сложным способом) иодин для имени искомого значения в указанном списке.Кнопка «Отправить» для каждого из этих текстовых полей с сообщением с указанием «Добавленная стоимость», когда она была добавлена, или «Найдена» «Не существует» для кнопки поиска.Затем на стороне указанных блоков и кнопок я фактически хочу отобразить мой список с прокручиваемым окном / блоком из 2 столбцов, первый столбец как позиция в табличном значении, в котором его значение at, а затем фактическое имя указанного добавленного значения,(О, кроме того, четкая кнопка для самого списка)

Итак, вот что я собрал до сих пор.Я понимаю, что должен преобразовать все входные данные в строку, а затем отправить ее в список.Я знаю, как отобразить MessageBox.Show(""), но не знаю, как кодировать условия для него.Я бы попробовал простой if (), но сначала мне нужно было бы запрограммировать работающую функцию поиска, которая требует извлечения и извлечения данных из списка.Я знаю, что в JavaScript есть array.push и array.indexof, что делает поиск и вставку объектов в массив довольно простым, но, насколько мне известно, в C # такой функции нет.

Я новичок в этом, поэтому любые советы по материалу для чтения, которые помогут мне изучить C #, или любые советы о том, как сделать эту работу должным образом, будут оценены.Моя самая большая проблема состоит в том, чтобы вернуть значение из указанного текстового поля в другое private void и использовать его в моем var, другими словами, передать произведение функции в другую функцию (как в примере ниже, нажав Add_Text.Textв var names = new List<string>();, который находится в другом пустоте над ним. Во всяком случае, здесь мое кодирование или неудачная попытка заставить это несколько «работать».

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace ArrayApp
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        // ARRAY CODING / LIST CODING

        public class Values
        {
            public string Position { get; set; } = string.Empty;

            public string Name { get; set; } = string.Empty;

        }

        public void App()
        {
            var names = new List<string>();

        }

        // BUTTON CLICKS / BUTTON ACTION CODING

        private void Add_Button_Click(object sender, RoutedEventArgs e)
        {
            List_Box.Content = Add_Text.Text;
            MessageBox.Show("Value Added");
            Add_Text.Clear();
        }

        private void Search_Button_Click(object sender, RoutedEventArgs e)
        {

        }

        // TEXT BOXES / WHAT BUTTON ACTUALLY INPUTS INTO OUR DISPLAY

        private void Add_Text_TextChanged(object sender, TextChangedEventArgs e)
        {

        }

        private void Search_Text_TextChanged(object sender, TextChangedEventArgs e)
        {

        }

        // DISPLAY - List_Box not added yet

    }
 }

Ответы [ 2 ]

0 голосов
/ 05 марта 2019

Итак, после некоторого чтения, а также ваших комментариев очень помогло, я думаю, что я освоился с этим и получил некоторое базовое понимание C #, по крайней мере, как он работает логически.Это «финальная» версия УДИВИТЕЛЬНОЙ программы, которую я пытался создать.Спасибо всем за помощь!

PS Комментарии для меня, чтобы узнать и ссылаться в будущем, когда я учусь C # или забыть вещи:)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;


/* QUICK TERMINOLOGY

    List = An Array that constantly adjusts its maximum size

    names = Our actual "database" or table with our values that we've inputted

    List_Box = The display table that is visible on the program itself

    var = Variable... You know...

    "public" or "private" = Those define whether the function is visible to the rest of the program or other "sheets" in the program

    void = Defines whether the return value or the output of a function should be something, void means not specified, 
            if you want string you put string, if you want an integer you put int... etc etc.

*/



namespace ArrayApp
{
    public partial class MainWindow : Window
    {

        /* Private Function for Creating the List which will be a String
        We are using a List instead of an Array as an Array needs 
        a specific amount of indexes so if we have a specific number of data or 
        a maximum amount of data that a user can input then array would be used
        but since we don't know how many indexes we need a list will automatically
        adjust the maximum size of our table to suit our needs. I.e. limitless  */

        private List<string> names;
        public MainWindow()
        {
            InitializeComponent();
            names = new List<string>();

        }

        /* Class for our Items in our list this is not referring the list above but...
        the list that it displays as we have a search on demand
        but also allows us to search for specific people in the List (array/table) rather than
        display over 100+ people, if our database was to get to that size.

        Our class function defines what data can be put into our Display List ( List_Box ) 
        Therefore the index can only be an integer and name can only be a string
        more on this later.  */

        class Items
        {
            public int Index { get; set; }
            public string Name { get; set; }
        }

        /* The Add Button Function
        This button takes the content of the TextBox that is right next to it and 
        adds it to our list called "names" but does not update our display, instead
        it shows us a message stating that the value was added to the list.
        If we were using an Array with a limited size, we could use an IF to check
        if there is a space available and output a message saying "Full" or "Failed"  */

        private void Add_Button_Click(object sender, RoutedEventArgs e)
        {
            names.Add(Add_Text.Text); // Adds the value

            Add_Text.Clear(); // Clears the text box

            MessageBox.Show("Value Added"); // Displays a message
        }


        /* Firstly...

         * We have an IF function that checks whether "names" contains the content
                of the search box, so if its a letter "a", it checks if its in our list.
         * It then creates a variable "SearchText" that we can later use that simply
                means that instead of writing the whole code we can just refer to it by our new name
         * Another variable! This one defines our Index in our list, it takes
                our previous variable and looks for it in our list and finds what
                the index number of that value is.
         * Now, since its Search on demand we essentially have two Lists (arrays) now
                that we have the name of the value we looking for in string format,
                we also have our index as integer (defined earlier in class). We need to take that data
                and add it to our display List and for that we have our function.
                Adds new Items to our list using the Items Class and also defines
                what data should be put into each column.
         * It then clears the search text box
         * and shows us that the value has been found.

         We then move to ELSE which is simple really...

            * Didn't find data
            * Clears search text box
            * Displays message that its not been found...  */


        private void Search_Button_Click(object sender, RoutedEventArgs e)
        {
            if (names.Contains(Search_Text.Text))  // Our If statement
            {
                var SearchText = Search_Text.Text;  // First Variable

                var FindIndex = names.IndexOf(SearchText);  // Second Variable

                List_Box.Items.Add(new Items() { Index = FindIndex, Name = SearchText});  // Adding items to display list

                Search_Text.Clear();  // Clear search text box

                MessageBox.Show("Data Found"); // Display message
            }
            else
            {
                Search_Text.Clear();

                MessageBox.Show("Not Found");
            };
        }

        /* Lastly a simple clear button for our display list.
         * Once a user searches for many values and wants to clear the display list
         * he can do it by hitting a single button.
         * 
         * This button DOES NOT delete anything from our "names" list it only
         * clears the display data meaning that the user can search for more data
         * that has been added already.  */


        private void Clear_Button_Click(object sender, RoutedEventArgs e)
        {
            List_Box.Items.Clear();
        }

        private void Add_Text_TextChanged(object sender, TextChangedEventArgs e)
        {

        }

        private void Search_Text_TextChanged(object sender, TextChangedEventArgs e)
        {

        }

        private void ListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

    }
 }

Воткак это выглядит, просто, но вы поняли, я учусь ...

0 голосов
/ 05 марта 2019

Давайте пройдемся по этому.Как вы уже упоминали, вам нужно что-то для хранения ваших данных.List хорошая идея, так как вы не знаете размер.В настоящее время вы создаете List типа string, который будет работать.
На самом деле класс Values не нужен, потому что вы можете получить индекс элемента с помощью функции * 1006.* - но позже больше.

Теперь, когда вы показываете MessageBox при добавлении элемента, вы также должны фактически добавить его в свой список names.Для этого объявите List в своем классе и инициализируйте его в своем конструкторе.Таким образом, вы сможете получить к нему доступ из любой точки вашего класса.

private List<string> names;
public void MainWindow()
{
    InitializeComponent();
    names = new List<string>();
}

Добавление элементов можно выполнить методом .Add, это довольно просто.

private void Add_Button_Click(object sender, RoutedEventArgs e)
{
    List_Box.Content = Add_Text.Text;
    MessageBox.Show("Value Added");

    names.Add(Add_Text.Text); // Adding the content of Add_text.Text

    Add_Text.Clear();
}

Поиск предмета тоже довольно прост.Просто используйте Contains, если вы хотите узнать, существует ли элемент, или IndexOf, если вы хотите иметь индекс.Примечание: IndexOf возвращает -1, если ничего не может быть найдено.

private void Search_Button_Click(object sender, RoutedEventArgs e)
{
    if(names.Contains( SEARCH_TEXT.TEXT /* or wherever you get your pattern from */ )){
        // found, display this in some way
    } else {
        // not found, display this is some way
    }
}

SEARCH_TEXT.TEXT содержит шаблон, который вы ищете.Я не знаю, как вы назвали свой элемент управления, просто замените его.

Вот и все.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...