C# WPF|在Grid中添加自己的“控件”并处理列定义

os8fio9y  于 2023-10-22  发布在  C#
关注(0)|答案(1)|浏览(145)

我还在学习XAML和WPF。我希望能够创建我自己的网格与我自己的控制。我在函数中传递了网格和一个格式列表,其中包括格式(例如textbox或combobox)和名称。我希望它在新行中的每第三个控件之后开始,而不管列表中提供了多少控件。
不幸的是,代码并没有指向目标,看起来像这样:The Form
也许有人知道如何更好地解决它。它看起来不太好。有没有办法让它看起来既匀称又好看?

  1. public Grid GetGridWithMaskControls(Grid grid, List<Format> formats) {
  2. int columnIndex = 0;
  3. int rowIndex = 0;
  4. for(int i = 0; i < formats.Count; i++) {
  5. if(i % 3 == 0) {
  6. rowIndex++;
  7. columnIndex = 0;
  8. }
  9. grid.ColumnDefinitions.Add(new ColumnDefinition());
  10. RowDefinition row = new RowDefinition();
  11. row.Height = new GridLength(25);
  12. grid.RowDefinitions.Add(row);
  13. Label t1 = new Label();
  14. Format format = formats[i];
  15. t1.Content = format.FieldName;
  16. TextBox tb = new TextBox();
  17. tb.Height = 20;
  18. tb.Width = 120;
  19. Grid.SetColumn(tb, i);
  20. Grid.SetRow(tb,rowIndex);
  21. grid.Children.Add(tb);
  22. Grid.SetColumn(t1, i);
  23. Grid.SetRow(t1, rowIndex);
  24. grid.Children.Add(t1);
  25. columnIndex++;
  26. }
  27. return grid;
  28. }
kmbjn2e3

kmbjn2e31#

问题是你不必为每一行添加列定义。
我想你想要这样的输出:

  1. private void GenerateGrid()
  2. {
  3. for (int i = 0; i < 3; i++)
  4. {
  5. grid.ColumnDefinitions.Add(new ColumnDefinition());
  6. }
  7. int columnIndex = 0;
  8. int rowIndex = 0;
  9. for (int i = 0; i < formats.Count; i++)
  10. {
  11. if (i % 3 == 0)
  12. {
  13. rowIndex++;
  14. columnIndex = 0;
  15. RowDefinition row = new RowDefinition();
  16. row.Height = new GridLength(25);
  17. grid.RowDefinitions.Add(row);
  18. }
  19. Label t1 = new Label();
  20. Format format = formats[i];
  21. Grid.SetColumn(t1, i%3);
  22. Grid.SetRow(t1, rowIndex);
  23. grid.Children.Add(t1);
  24. t1.Content = format.FieldName;
  25. TextBox tb = new TextBox();
  26. tb.Height = 20;
  27. tb.Width = 120;
  28. Grid.SetColumn(tb, i%3);
  29. Grid.SetRow(tb, rowIndex);
  30. grid.Children.Add(tb);
  31. columnIndex++;
  32. }
  33. }
展开查看全部

相关问题