从动态创建的元素中获取价值

时间:2017-05-17 17:26:24

标签: c# visual-studio uwp

我正在从大学学习一个项目(UWP C sharp) 我需要建立图书馆程序来管理书籍和杂志 我的编辑项目页面有问题... iv创建的方法,通过所选项目的类型动态创建元素(文本框,日期选择器等)(如果用户选择书籍,他将获得与杂志相同的书籍元素...) 问题是当我试图编写事件按钮,从所有那些元素中获取值时,我无法达到它们...因为它们在方法中...  (如book.title = textbox.text;)

对不起我的英语和Ty的帮助:)

 private void CreateBtnsByTheTypeOfTheItem(AbstractItem item)
        {
            TextBox editTitleTB = new TextBox();
            editTitleTB.Text = LibManager.Instance.CurrentItem.Title;
            Grid.SetRow(editTitleTB, 0);
            editPageGrid.Children.Add(editTitleTB);

            CheckBox editIsAvaibleCB = new CheckBox();
            editIsAvaibleCB.Content = "Is Avaible";
            editIsAvaibleCB.IsChecked = item.isAvaible;
            Grid.SetRow(editIsAvaibleCB, 1);
            editPageGrid.Children.Add(editIsAvaibleCB);

            DatePicker editDatePicler = new DatePicker();
            editDatePicler.Date = item.PublishDate;
            Grid.SetRow(editDatePicler, 3);
            editPageGrid.Children.Add(editDatePicler);



            if (item is Book)
            {
                Book itemAsBook = item as Book;

                TextBox editAuthor = new TextBox();
                editAuthor.Text = itemAsBook.Author;
                Grid.SetRow(editAuthor, 2);
                editPageGrid.Children.Add(editAuthor);

                var _enumval = Enum.GetValues(typeof(BookCategory)).Cast<BookCategory>();

                ComboBox editCategpryCB = new ComboBox();
                editCategpryCB.ItemsSource = _enumval.ToList();
                editCategpryCB.SelectedItem = itemAsBook.Category;
                Grid.SetRow(editCategpryCB, 4);
                editPageGrid.Children.Add(editCategpryCB);
            }
            else
            {
                Magazine itemAsMagazine = item as Magazine;

                TextBox editEditors = new TextBox();
                editEditors.Text = itemAsMagazine.Editors;
                Grid.SetRow(editEditors, 2);
                editPageGrid.Children.Add(editEditors);

                var _enumval = Enum.GetValues(typeof(MagazineCategory)).Cast<MagazineCategory>();

                ComboBox editMagazineCategory = new ComboBox();
                editMagazineCategory.ItemsSource = _enumval.ToList();
                editMagazineCategory.SelectedItem = itemAsMagazine.Category;
                Grid.SetRow(editMagazineCategory, 4);
                editPageGrid.Children.Add(editMagazineCategory);
            }

1 个答案:

答案 0 :(得分:0)

如果已为每个动态创建的字段命名,则可以使用FindName方法访问它们。

TextBox editTitleTB = new TextBox();
editTitleTB.Name = "TheHobbitTB";
editTitleTB.Text = LibManager.Instance.CurrentItem.Title;
TextBox theHobbitTB = (TextBox)this.FindName("TheHobbitTB");

然后,您基本上可以编辑该特定文本框的任何内容。