簡體   English   中英

在 WPF 中使用搜索欄(文本框)時如何重新排序 StackPanel?

[英]How to make a StackPanel reorder when using a Search Bar (TextBox) in WPF?

上下文:我有一個里面有按鈕的 StackPanel。 這些按鈕以編程方式創建、命名並放置在 stackPanel 中。 然后我有一個用作搜索欄的 TextBox,其中有一個用作搜索按鈕的按鈕。

我想要做什么:我想要這樣,當 TextBox 填充了某些 Button 標簽的 Text 並單擊 Search Button 時,StackPanel 會刪除似乎與 TextBox 內容不匹配的按鈕,然后當我擦除時TextBox 的內容重新出現(我不介意它的順序是否與以前相同)。

問題:我有兩個主要問題,都與同一個問題有關:單擊搜索按鈕時,它什么也沒成功。 通過 FindName 方法調用 Button 似乎不起作用(它給了我一個 null 。所以,我的問題是:是否可以像我之前那樣重新排序 StackPanel?在這種情況下,我將如何調用 Button以編程方式創建?

代碼:

private void buscarEntrada_Click(object sender, RoutedEventArgs e)
{
    //Search button's click event
    //All the buttons are named "Btn" + a constantly increasing number (0,1,2,3...)
    //stackBotones is my StackPanel, I remove the buttons and then readd them depending on the textbox's content
    try
    {
        for (int i = 0; i < stackBotones.Children.Count; i++)
        {
            stackBotones.Children.Remove((UIElement)stackBotones.FindName());
        }
    }
    catch (Exception error)
    {
        MessageBox.Show(error);
    }
}

預先感謝您閱讀本文。

您可以在Children集合中按名稱查找子元素,如下所示:

string name = txt.Text;
Button button = stackBotones.Children.OfType<Button>().FirstOrDefault(x => x.Name == name);

如果要刪除除匹配元素之外的所有元素,可以在循環中執行此操作:

string name = "b";
for(int i = stackBotones.Children.Count - 1; i>=0; i--)
{
    if (stackBotones.Children[i] is FrameworkElement fe && fe.Name != name)
        stackBotones.Children.RemoveAt(i);
}

您可以將stackBotones.Children[i]添加到一個列表中,然后您可以使用該列表根據您的邏輯重新填充stackBotones.Children

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM