繁体   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