0

我正在学习 c# 的基础知识。我正在使用 WPF。我想让列表框在从中选择项目后消失。我使用了 visibility=collapsed 但它在这里不起作用我的代码是:

<ListBox Foreground="White" Grid.Row="1" SelectionMode="Single" SelectionChanged="PrintText" Background="DarkGray" Visibility="Collapsed"  Height="Auto" HorizontalAlignment="Left" Margin="156,36,0,0" Name="listBox1" VerticalAlignment="Top" Width="191" UseLayoutRounding="True" />

private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
{
    if(autolist.Count>0)
    {
        listBox1.ItemsSource = autolist;
        listBox1.Visibility = Visibility.Visible;
        // a = pk;
    }
    else
    {
        listBox1.Visibility = Visibility.Collapsed;
        listBox1.ItemsSource = null;
    }
}

private void listBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    //selectedItemsId = (int)listBox1.SelectedValue;
    if (listBox1.ItemsSource != null)
    {
        listBox1.Visibility = Visibility.Collapsed;
        textBox1.TextChanged += new TextChangedEventHandler(textBox1_TextChanged);
    }

    if (listBox1.SelectedIndex != -1)
    {
        textBox1.Text = listBox1.SelectedItem.ToString();
        textBox1.TextChanged += new TextChangedEventHandler(textBox1_TextChanged);
    }
}
4

2 回答 2

1

没有发生任何事情,因为您定义了一个名称与您在 XAML 中调用的名称不同的事件处理程序。

您的列表框尝试触发PrintText,但我可以在您的代码中看到,您希望它改为触发listBox1_SelectionChanged

像这样更改您的 XAML:

<ListBox Foreground="White" Grid.Row="1" SelectionMode="Single" SelectionChanged="listBox1_SelectionChanged" Background="DarkGray" Visibility="Collapsed"  Height="Auto" HorizontalAlignment="Left" Margin="156,36,0,0" Name="listBox1" VerticalAlignment="Top" Width="191" UseLayoutRounding="True" />

此外,为了防止文本框更改事件将列表框设置回可见,请在列表框事件处理程序中尝试类似的操作

private void listBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //selectedItemsId = (int)listBox1.SelectedValue;
            if (listBox1.ItemsSource != null)
            {
                listBox1.Visibility = Visibility.Collapsed;
            }

            if (listBox1.SelectedIndex != -1)
            {
                //remove the listener on the textbox
                textBox1.TextChanged -= TextBoxBase_OnTextChanged;
                textBox1.Text = listBox1.SelectedItem.ToString();
                //put the listener back on the text box
                textBox1.TextChanged += TextBoxBase_OnTextChanged;
            }
        }
于 2013-07-01T16:14:55.243 回答
-1

你可以写:

listBox1.Visible = false;

而不是 listBox1.Visibility。

于 2013-07-01T16:05:14.210 回答