简体   繁体   English

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

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

CONTEXT: I have a StackPanel with Buttons inside.上下文:我有一个里面有按钮的 StackPanel。 These buttons are created, named and put inside the stackPanel programmatically.这些按钮以编程方式创建、命名并放置在 stackPanel 中。 Then I have a TextBox serving as a Search bar with a button that is utilised as search button.然后我有一个用作搜索栏的 TextBox,其中有一个用作搜索按钮的按钮。

WHAT I WANT TO DO: I want that, when the TextBox is filled with the Text of certain Button's Label and the Search Button is clicked, the StackPanel removes the buttons that do not seem to match with the TextBox content and then, when I erase the TextBox's content, reappear (I don't mind if it's in the same order than before or not).我想要做什么:我想要这样,当 TextBox 填充了某些 Button 标签的 Text 并单击 Search Button 时,StackPanel 会删除似乎与 TextBox 内容不匹配的按钮,然后当我擦除时TextBox 的内容重新出现(我不介意它的顺序是否与以前相同)。

PROBLEM: I have two main problems, both related to the same: when the Search Button is clicked, it succeeds nothing.问题:我有两个主要问题,都与同一个问题有关:单击搜索按钮时,它什么也没成功。 Invoking a Button by FindName method doesn't seem to work (it gives me a null . So, my question is: Is it possible to make the StackPanel reorder as I put before? In that case, how would I do that calling the Button created programmatically?通过 FindName 方法调用 Button 似乎不起作用(它给了我一个 null 。所以,我的问题是:是否可以像我之前那样重新排序 StackPanel?在这种情况下,我将如何调用 Button以编程方式创建?

CODE:代码:

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);
    }
}

Thank you in advance for reading this.预先感谢您阅读本文。

You can find a child element by its name in the Children collection like this:您可以在Children集合中按名称查找子元素,如下所示:

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

If you want to remove all elements but the matching one, you could do this in a loop:如果要删除除匹配元素之外的所有元素,可以在循环中执行此操作:

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);
}

You may add stackBotones.Children[i] to a list that you then use to repopulate stackBotones.Children based on your logic.您可以将stackBotones.Children[i]添加到一个列表中,然后您可以使用该列表根据您的逻辑重新填充stackBotones.Children

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM