从中选择项目后如何隐藏列表框?

时间:2013-07-01 16:02:53

标签: c# .net wpf

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

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

2 个答案:

答案 0 :(得分: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;
            }
        }

答案 1 :(得分:-1)

你可以写:

listBox1.Visible = false;

而不是listBox1.Visibility。