2017-03-06 120 views
-1

所以我試圖在C#中的WPF中生成一個動態的按鈕列表,但我發現它非常困難。無論我如何嘗試這樣做,我都會得到'Button'不包含''的定義的錯誤(在這種情況下爲Text和Dock,然後我無法轉換Controls.Add中的按鈕(b )line。我真的不知道發生了什麼,但是我在StackOverflow上找到的解決方案已經解決了這個問題,所以我覺得我應該請別人解釋這裏發生了什麼問題 感謝任何花時間幫忙的人!C#生成按鈕的動態列表

using System; 
using System.Collections.Generic; 
using System.Windows; 
using System.Windows.Controls; 
using System.Windows.Forms; 

namespace App_Manager 
{ 
    public partial class GroupListScreen : Window 
    { 
     SQLiteManager SQLMan; 
     public GroupListScreen(SQLiteManager SQLman) 
     { 
     SQLMan = SQLman; 
     GenerateList(); 
     InitializeComponent(); 
     } 

     private void GenerateList() 
     { 
      TableLayoutPanel tableLayoutPanel1 = new TableLayoutPanel(); 
      List<QueryData> listGenerate = SQLMan.getData(); 
      var rowCount = listGenerate.Count/3; 
      var columnCount = 3; 

      tableLayoutPanel1.ColumnCount = columnCount; 
      tableLayoutPanel1.RowCount = rowCount; 

      tableLayoutPanel1.ColumnStyles.Clear(); 
      tableLayoutPanel1.RowStyles.Clear(); 

      for (int i = 0; i < columnCount; i++) 
      { 
      tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100/columnCount)); 
      } 
      for (int i = 0; i < rowCount; i++) 
      { 
      tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100/rowCount)); 
      } 

      for (int i = 0; i < rowCount * columnCount; i++) 
      { 
       System.Windows.Controls.Button b = new System.Windows.Controls.Button(); 
       b.Text = (i + 1).ToString(); 
       b.Name = string.Format("b_{0}", i + 1); 
       b.Click += b_Click; 
       b.Dock = DockStyle.Fill; 
       tableLayoutPanel1.Controls.Add(b); 
      } 
     } 
    } 
} 
+0

在'GenerateList()'之前放置'InitializeComponent()'方法' –

+3

WPF不是Winforms。如果你想寫Winforms代碼,你應該使用Winforms。如果你想使用WPF,你需要學習WPF習慣用法。上述任務最好通過使用數據模板解決,而不是在代碼中生成元素。如果你必須在代碼中生成元素,你需要明白'Button'有'Content'屬性,而不是'Text','TableLayoutPanel'是一個Winforms對象,你真的不應該試圖在WPF中使用它。 –

+0

@PeterDuniho感謝您的意見,即使我使用'wpf'這個東西出現了,但我對這些東西並不是非常有經驗,所以我不太瞭解。 – BadJukeBox

回答

0

你應該開始使用WPF時開始MVVM 它是生成動態列表很容易的事簡短的摘要:。一個ObservableCollection,並在您查看與ItemsTemplate的如ListView的,這就是它無碼需要後面;)