从字符串生成文本框到网格中

时间:2016-05-24 05:39:52

标签: c# xaml uwp uwp-xaml

我想在gridview中生成文本框。每个文本框都包含字符串中的char(此字符串是从文本框Text Changed事件处理程序中获取的)。

Example:
string = hello,
I would like to generate 5 textboxes, each contains "h", "e", "l", "l", "o".

我自己实现了应用程序,但是遇到了性能问题,当字符串长度为>时,应用程序非常滞后。 30个字符(当我在文本框中输入时,文本框生成的速度比输入慢得多,除了我的输入在文本框中出现之前是延迟)

我可以知道如何改善这个问题? (我很确定,对于今天的PC,这应该不是性能问题......)

代码:

 // main.cs
 private ObservableCollection<MenuSettings> gridCollection;

        public MainPage()
        {
            this.InitializeComponent();
            this.gridCollection = new ObservableCollection<MenuSettings>();

            gridView.ItemsSource = this.gridCollection;            
        }

        private void textBox_name_TextChanged(object sender, TextChangedEventArgs e)
        {
            var collections = MenuSettings.Convert(textBox_name.Text);
            int gridCollectionLength = this.gridCollection.Count;
            int diff = collections.Count - gridCollectionLength;

            for (int i = 0; i < Math.Abs(diff); i++) {
                if (diff > 0) {
                    this.gridCollection.Add(new MenuSettings());
                } else {
                    this.gridCollection.RemoveAt(gridCollectionLength - i - 1);
                }
            }

            for (int i = 0; i < this.gridCollection.Count; i++) {
                this.gridCollection[i] = collections[i];
            }
        }

// menusetting.cs
 public class MenuSettings
    {
        private SolidColorBrush selected;

        public string Title { set; get; }
        public SolidColorBrush Selected { set; get; }


        public static List<MenuSettings> Convert(string text)
        {
            return text.ToCharArray().Select((x, i) => {
                return new MenuSettings()
                {
                    Title = x.ToString()
                };
            }).ToList();
        }
    }


<TextBox x:Name="textBox_name" Text="hello! this is so cool!"
                 TextChanged="textBox_name_TextChanged"
                 SelectionChanged="textBox_name_SelectionChanged" />
        <GridView x:Name="gridView">
            <GridView.ItemTemplate>
                <DataTemplate x:DataType="local:MenuSettings">
                    <TextBox Text="{x:Bind Title}"
                             Background="{x:Bind Selected}" />
                </DataTemplate>
            </GridView.ItemTemplate>
        </GridView>

0 个答案:

没有答案