简体   繁体   中英

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

CONTEXT: I have a StackPanel with Buttons inside. These buttons are created, named and put inside the stackPanel programmatically. Then I have a TextBox serving as a Search bar with a button that is utilised as search button.

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).

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?

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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