C# 在Stackpanel中排序动态用户控件

C# 在Stackpanel中排序动态用户控件,c#,wpf,sorting,controls,stackpanel,C#,Wpf,Sorting,Controls,Stackpanel,我有一个用户控件,它有多个包含值的标签,例如上载日期、标题字符串、作者字符串等。 现在,我通过为SQL数据库中的每一行数据创建一个新的用户控件实例来填充stackpanel 我希望单击“按日期排序”按钮,并在Stackpanel中按上载日期对用户控件对象的所有实例进行排序 我该如何处理这件事 使用用户控件的新实例填充stackpanel背后的一些代码 /// <summary> /// Receive data from SQL and apply them to a new ins

我有一个用户控件,它有多个包含值的标签,例如上载日期、标题字符串、作者字符串等。 现在,我通过为SQL数据库中的每一行数据创建一个新的用户控件实例来填充stackpanel

我希望单击“按日期排序”按钮,并在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();
    }
}
//
///从SQL接收数据并将其应用于itemControl的新实例
/// 
公共静态void GetResultItems(StackPanel StackPanel)
{
//SQL查询
string Query=“从项目中选择*”;
MySqlCommand=newmysqlcommand(查询、连接);
//开放连接
connection.Open();
MySqlDataReader=command.ExecuteReader();
//在阅读的时候。。。
while(reader.Read())
{
//创建itemControl的新实例
ItemControl ItemControl=新的ItemControl();
//将SQL数据库中的数据分配到itemControl标签上
//上载日期。它包含上载的日期。
itemControl.lbllistupload.Content=(reader[“UploadDate”].ToString());//我希望使用此值进行排序
//作者
itemControl.lblExpandAuthor.Content=“Author:”+(reader[“Author”].ToString());
//将ItemControl的新实例添加到resultItem列表中
//该列表从未使用过,但会在以后使用/需要时创建。
结果添加(项目控制);
//将项目添加到Stackpanel
stackPanel.Children.Add(itemControl);
}
//密切联系
connection.Close();
}
}
怎么样

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

你的问题太宽泛了。一个显而易见的解决方案当然是通过修改查询,让数据按排序顺序返回。如果您不能这样做,那么通常的WPF方法是对源数据应用
CollectionViewSource
,并在其中设置排序选项。然而,如果您没有像这里这样从坏的WPF代码开始,那么这是最好的。也就是说,您不应该直接操作UI对象;相反,请绑定集合并使用具有更多数据绑定的模板来控制可视化显示。如果我没有弄错的话,这将只对SQL数据库中的行进行排序,而不会在客户端进行排序,对吗?@Trinax您将在客户端获得排序结果。