Изменение содержимого ContentDialog из другого метода - PullRequest
0 голосов
/ 10 октября 2018

Я начинающий программист, и это моя первая программа, поэтому, пожалуйста, будьте милы со мной.У меня есть странная ситуация, когда мне нужно получить доступ к элементам ContentDialog из другого метода.И так как мой английский ужасен, и я не могу объяснить, что происходит, я просто опубликую код здесь.

private async void PointsButton_Click(object sender, RoutedEventArgs e)
{
    // this one should modify the student's points , and the problem is here
    StackPanel ptsdialog = new StackPanel
    {
        Orientation = Orientation.Horizontal,
        HorizontalAlignment = HorizontalAlignment.Center
    };
    TextBlock pts = new TextBlock // this is the text block that should show the points and change the value when they are modified
    {
        Name = "pts",
        Text = FileContent[Names.SelectedIndex].StuPoints.ToString(), // i know this will not change over time , but just presnting what should be viewed
        FontSize = 32,
        HorizontalAlignment = HorizontalAlignment.Stretch,
        VerticalAlignment = VerticalAlignment.Stretch,
        Margin = new Thickness(8, 0, 8, 0)
    };
    Button plus = new Button();
    plus.Click += Plus_Click; // one of the methods that should modify the text block
    plus.Content = "+10";

    Button minus = new Button();
    minus.Click += Minus_Click; // the other method
    minus.Content = "-10";
    ptsdialog.Children.Insert(0, plus);
    ptsdialog.Children.Insert(1, pts);
    ptsdialog.Children.Insert(2, minus);
    ContentDialog deleteFileDialog = new ContentDialog
    {
        Title = "عدل نقاط الطالب",
        Content = ptsdialog,
        PrimaryButtonText = "نعديل",
        CloseButtonText = "إلغاء"
    };

    ContentDialogResult result = await deleteFileDialog.ShowAsync();

    if (result == ContentDialogResult.Primary)
    {
        Student student = new Student()
        {
            StuName = FileContent[Names.SelectedIndex].StuName,
            StuClass = FileContent[Names.SelectedIndex].StuClass,
            StuGroup = FileContent[Names.SelectedIndex].StuGroup,
            StuPoints = int.Parse(pts.Text),// only chages the points
            EnterDate = FileContent[Names.SelectedIndex].EnterDate,
            StuAtts = FileContent[Names.SelectedIndex].StuAtts
        };
        WriteToFile(student, Names.SelectedIndex, false);

    }
}

private void Minus_Click(object sender, RoutedEventArgs e)
{
    pts.Text = (int.Parse(pts.Text) - 10).ToString(); // this will not work , but just presenting what i want to do
}

private void Plus_Click(object sender, RoutedEventArgs e)
{
    pts.Text = (int.Parse(pts.Text) + 10).ToString(); // this will not work , but just presenting what i want to do
}

Что я хочу сделать, так это то, что при нажатии кнопки «плюс»значение текста в текстовом блоке увеличивается на десять, и то же самое для кнопки минус

Проблема здесь в том, что я пытаюсь найти элемент, который существует в другом контексте, но я не могу найти какой-либо способ обойтиэта ошибка.

Вот весь код для справки.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Storage;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using System.ComponentModel;

namespace App1
{        
    public class Student
    {
        public string StuName { get; set; } // Stu stands for student
        public int StuClass { get; set; }
        public int StuGroup { get; set; }
        public int StuPoints { get; set; }
        public DateTime EnterDate { get; set; }
        public string StuAtts { get; set; } 
    }
    public sealed partial class MainPage : Page
    {
        public static string dataFilePath = ApplicationData.Current.LocalFolder.Path + @"\data.nn"; // file path that stores the student's data
        public IList<string> UnffileContent { get; set; } = new List<string>(); // unprocessed data in form of strings
        public IList<Student> FileContent { get; set; } = new List<Student>() ; // processed data 

        public static string[] classes = {"فصل 1/1", "فصل 1/2", "فصل 1/3", "فصل 1/4", "فصل 1/5", "فصل 1/6", "فصل 2ط/1", "فصل 2ط/2", "فصل 2ط/3", "فصل 2ط/4", "فصل 2ط/5", "فصل 2ش/1", "فصل 3ط/1", "فصل 3ط/2", "فصل 3ط/3", "فصل 3ط/4", "فصل 3ط/5","فصل 3ش/1", "فصل 3ش/2" }; // list of classes in my school for reference
        public static string[] groups = {"النماء","التميز","العلو","السمو","الابتكار"}; // list of groups

        public MainPage()
        {
            InitializeComponent(); 
        }

        private void PPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (!File.Exists(dataFilePath))
            {
                File.Create(dataFilePath).Dispose(); // creates the file if it does not exist
            }

            ReadFromfile(); 
        }

        public void ReadFromfile()
        {
            UnffileContent = File.ReadAllLines(dataFilePath).ToList();
            FileContent = new List<Student>(); // resets the file content list
            foreach (string line in UnffileContent)
            {
                string[] Stuline = line.Split("$"); // data is written like "name$class$group$points$date$atts"
                FileContent.Add(new Student()
                {
                    StuName = Stuline[0],
                    StuClass = int.Parse(Stuline[1]),
                    StuGroup = int.Parse(Stuline[2]),
                    StuPoints = int.Parse(Stuline[3]),
                    EnterDate = DateTime.ParseExact(Stuline[4], "yyyy/MM/dd", null),
                    StuAtts = Stuline[5]
                });
            };
            Names.ItemsSource = new List<Student>(); // Names is a list view that views names of all students
            Names.ItemsSource = FileContent; 
        }

        public void WriteToFile(Student stu, int index, bool isnew)
        {
            if (isnew) 
            {
                // create a new empty student and make him last
                FileContent.Add(new Student());
                index = FileContent.Count - 1;
            }
            FileContent[index] = stu; // set the student in the index to new student value
            SaveFile();
        }

        public void SaveFile ()
        {
            File.Delete(dataFilePath);
            File.Create(dataFilePath).Dispose(); // resets the file
            UnffileContent = new List<string>(); // resets the unprocessed list to modify it later
            foreach (Student stu in FileContent)
            {
                object[] stuarr = new object[6] { stu.StuName, stu.StuClass, stu.StuGroup, stu.StuPoints, stu.EnterDate.ToString("yyyy/MM/dd"), stu.StuAtts }; // creates an array of every element in student
                string processedstr = string.Join("$", stuarr); // forms the "name$class$group$points$date$atts" format
                UnffileContent.Add(processedstr); // adds the format to the unprocessed list
            }
            File.WriteAllLines(dataFilePath, UnffileContent); // write the new data in the empty file
            ReadFromfile(); // recalls reading

        }

        private void Pass_PasswordChanged(object sender, RoutedEventArgs e)
        {
            if (Pass.Password == "نادينون") // make everything visible and hide the password box if password is correct
            {
                Pass.Visibility = Visibility.Collapsed;
                TitleTextBlock.Visibility = 0;
                Nav.Visibility = 0;
            }
        }

        private void Names_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (Names.SelectedIndex > -1)
            {
                // show UI buttons if an item is selected
                BDeleteB.Visibility = Visibility.Visible;
                BEditB.Visibility = Visibility.Visible;
                BPointsB.Visibility = Visibility.Visible;
                BattB.Visibility = Visibility.Visible;    
            }
            else
            {
                // hide UI buttons if an item is not selected
                BDeleteB.Visibility = Visibility.Collapsed;
                BEditB.Visibility = Visibility.Collapsed;
                BPointsB.Visibility = Visibility.Collapsed;
                BattB.Visibility = Visibility.Collapsed;
            }
        }

        public async void AddButton_Click(object sender, RoutedEventArgs e)
        {
            // this will display a content dialog with a panel and some elements inside it
            // it will ask the user to insert new student data to save it later
            StackPanel adddialog = new StackPanel
            {
                Orientation = Orientation.Horizontal,
                Width = 384
            };
            TextBox name = new TextBox
            {
                Header = "الاسم:",
                PlaceholderText = "فلان فلان الفلاني",
                Width = 160,
                Margin = new Thickness(0,0,8,0)
            };
            ComboBox dclass = new ComboBox
            {
                Header = "الصف:",
                PlaceholderText = "اختر الفصل",
                ItemsSource = classes,
                Margin = new Thickness(0,0,8,0),
                Width = 80

            };
            ComboBox group = new ComboBox
            {
                Header = "المجموعة:",
                PlaceholderText = "اختر المجموعة",
                ItemsSource = groups,
                Width = 120
            };
            adddialog.Children.Insert(0, name);
            adddialog.Children.Insert(1, dclass);
            adddialog.Children.Insert(2, group);
            ContentDialog deleteFileDialog = new ContentDialog
            {
                Title = "أضف بيانات الطالب الجديد",
                Content = adddialog,
                PrimaryButtonText = "إضافة",
                CloseButtonText = "إلغاء"
            };

            ContentDialogResult result = await deleteFileDialog.ShowAsync();

            if (result == ContentDialogResult.Primary) // adds a new student with the info given
            {
                Student student = new Student() {
                    StuName = name.Text,
                    StuClass = dclass.SelectedIndex,
                    StuGroup = group.SelectedIndex,
                    StuPoints = 0,
                    EnterDate = DateTime.Now,
                    StuAtts = "nnnnnnnnn"
                };
                WriteToFile(student, -1, true);

            }
        }

        private void DeleteButton_Click(object sender, RoutedEventArgs e) // deletes selected students then saves the file
        {
            int delindex = Names.SelectedIndex;
            FileContent.RemoveAt(delindex);
            SaveFile();
        }

        private async void EditButton_Click(object sender, RoutedEventArgs e)
        {
            // similar to the first one but a little bit different elements
            // this should edit the elected student from the names list view
            StackPanel editdialog = new StackPanel
            {
                Orientation = Orientation.Horizontal,
                Width = 384
            };
            TextBox name = new TextBox
            {
                Header = "الاسم:",
                PlaceholderText = "فلان فلان الفلاني",
                Width = 160,
                Margin = new Thickness(0, 0, 8, 0),
                Text = FileContent[Names.SelectedIndex].StuName
            };
            ComboBox dclass = new ComboBox
            {
                Header = "الصف:",
                PlaceholderText = "اختر الفصل",
                ItemsSource = classes,
                Margin = new Thickness(0, 0, 8, 0),
                Width = 80,
                SelectedIndex = FileContent[Names.SelectedIndex].StuClass
            };
            ComboBox group = new ComboBox
            {
                Header = "المجموعة:",
                PlaceholderText = "اختر المجموعة",
                ItemsSource = groups,
                Width = 120,
                SelectedIndex = FileContent[Names.SelectedIndex].StuGroup
            };
            editdialog.Children.Insert(0, name);
            editdialog.Children.Insert(1, dclass);
            editdialog.Children.Insert(2, group);
            ContentDialog deleteFileDialog = new ContentDialog
            {
                Title = "عدل بيانات الطالب",
                Content = editdialog,
                PrimaryButtonText = "نعديل",
                CloseButtonText = "إلغاء"
            };

            ContentDialogResult result = await deleteFileDialog.ShowAsync();

            if (result == ContentDialogResult.Primary)
            {
                Student student = new Student() // edits the new student with the given info
                {
                    StuName = name.Text,
                    StuClass = dclass.SelectedIndex,
                    StuGroup = group.SelectedIndex,
                    StuPoints = FileContent[Names.SelectedIndex].StuPoints,
                    EnterDate = FileContent[Names.SelectedIndex].EnterDate,
                    StuAtts = FileContent[Names.SelectedIndex].StuAtts
                };
                WriteToFile(student, Names.SelectedIndex, false);

            }
        }

        private async void PointsButton_Click(object sender, RoutedEventArgs e)
        {
            // this one should modify the student's points , and the problem is here
            StackPanel ptsdialog = new StackPanel
            {
                Orientation = Orientation.Horizontal,
                HorizontalAlignment = HorizontalAlignment.Center
            };
            TextBlock pts = new TextBlock // this is the text block that should show the points and change the value when they are modified
            {
                Name = "pts",
                Text = FileContent[Names.SelectedIndex].StuPoints.ToString(), // i know this will not change over time , but just presnting what should be viewed
                FontSize = 32,
                HorizontalAlignment = HorizontalAlignment.Stretch,
                VerticalAlignment = VerticalAlignment.Stretch,
                Margin = new Thickness(8, 0, 8, 0)
            };
            Button plus = new Button();
            plus.Click += Plus_Click; // one of the methods that should modify the text block
            plus.Content = "+10";

            Button minus = new Button();
            minus.Click += Minus_Click; // the other method
            minus.Content = "-10";
            ptsdialog.Children.Insert(0, plus);
            ptsdialog.Children.Insert(1, pts);
            ptsdialog.Children.Insert(2, minus);
            ContentDialog deleteFileDialog = new ContentDialog
            {
                Title = "عدل نقاط الطالب",
                Content = ptsdialog,
                PrimaryButtonText = "نعديل",
                CloseButtonText = "إلغاء"
            };

            ContentDialogResult result = await deleteFileDialog.ShowAsync();

            if (result == ContentDialogResult.Primary)
            {
                Student student = new Student()
                {
                    StuName = FileContent[Names.SelectedIndex].StuName,
                    StuClass = FileContent[Names.SelectedIndex].StuClass,
                    StuGroup = FileContent[Names.SelectedIndex].StuGroup,
                    StuPoints = int.Parse(pts.Text),// only chages the points
                    EnterDate = FileContent[Names.SelectedIndex].EnterDate,
                    StuAtts = FileContent[Names.SelectedIndex].StuAtts
                };
                WriteToFile(student, Names.SelectedIndex, false);

            }
        }

        private void Minus_Click(object sender, RoutedEventArgs e)
        {
            pts.Text = (int.Parse(pts.Text) - 10).ToString(); // this will not work , but just presenting what i want to do
        }

        private void Plus_Click(object sender, RoutedEventArgs e)
        {
            pts.Text = (int.Parse(pts.Text) + 10).ToString(); // this will not work , but just presenting what i want to do
        }

        private void AttsButton_Click(object sender, RoutedEventArgs e)
        {
            // future use
        }
    }
}
...