![](/img/trans.png)
[英]How to compare the items of two list-boxes and copy the unique items to new list-box
[英]how to hide a list-box after selecting items from it?
我正在學習C#的基礎知識。 我使用WPF。 我要使列表框從中選擇項目后消失。 我使用了能見度=折疊,但是在這里不起作用,我的代碼是:
<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);
}
}
什么也沒發生,因為您定義的事件處理程序的名稱與您在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;
}
}
你可以寫:
listBox1.Visible = false;
而不是listBox1.Visibility。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.