2017-07-20 61 views
0

我有一个用户控件,它有多个标签包含值,例如Uploaded的日期,Title的字符串,Author的字符串等。 截至目前,我通过为SQL数据库中的每一行数据创建用户控件的新实例来填充堆栈面板。在Stackpanel中排序动态用户控件

我想要的是点击“按日期排序”按钮,并使用户控制对象的所有实例按照Stackpanel中的上传日期排序。

我怎么会这样做呢?

用户控件的新实例填充堆栈面板后的一些代码。

/// <summary> 
/// Receive data from SQL and apply them to a new instance of itemControl 
/// </summary> 
public static void GetResultItems(StackPanel stackPanel) 
{ 
    // The SQL Query 
    string Query = "select * from Items"; 
    MySqlCommand command = new MySqlCommand(Query, connection); 

    // Open connection 
    connection.Open(); 
    MySqlDataReader reader = command.ExecuteReader(); 

    // While reading... 
    while (reader.Read()) 
    { 
    // Creates new instance of the itemControl 
    ItemControl itemControl = new ItemControl(); 

    // Assign the data from the SQL database onto the itemControl labels 
    //Upload Date. This contains the date for when it was Uploaded. 
    itemControl.lblListUploaded.Content = (reader["UploadDate"].ToString()); //I wish to use this value to sort by 

    //Author 
    itemControl.lblExpandAuthor.Content = "Author: " + (reader["Author"].ToString()); 

    // Add the new instance of ItemControl to the resultItem List<> 
    //The list is never used, but is created incase of later usage/need. 
    resultItem.Add(itemControl); 

    // Add the item to the Stackpanel 
    stackPanel.Children.Add(itemControl); 
    } 

    // Close connection 
    connection.Close(); 
    } 
} 

This is a photo of how the Stackpanel looks

+0

你的问题是如何的方式过于宽泛。一个明显的解决方案当然是通过修改查询来按照排序顺序返回数据。如果你不能这样做,那么通常的WPF方法就是将“CollectionViewSource”应用于源数据并在其中设置排序选项。但是,如果您不是从破碎的WPF代码开始,那么这种方法效果最好,就像您在这里一样。即你不应该直接操纵UI对象;相反,绑定您的收藏并使用具有更多数据绑定的模板来控制视觉呈现。 –

回答

0

string Query = "select * from Items orderby UploadDate"; 
+0

如果我没有弄错,这只会对SQL数据库中的行进行排序,而不是在客户端进行排序,对吗? – Trinax

+0

@Trinax您将在客户端获得排序结果。 –

+0

这工作完美。谢谢! – Trinax