我有一个简单的清单;一切正常,但是当我单击按钮并且列表为empy时,元素之间会出现空白区域。我该如何删除它?
private void button1_Click(object sender, RoutedEventArgs e)
{
if (textBox1.Text=="")
{
MessageBox.Show("Campul este liber!");
}
//ListBox li = sender as ListBox;
ListBoxItem li = new ListBoxItem();
li.Content=textBox1.Text;
textBox1.Clear();
listBox1.Items.Add(li);
textBox1.Focus();
}
代码xaml:
<Window x:Class="Lista.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="250" Width="325">
<Grid>
<Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="203,176,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
<ListBox Height="111" HorizontalAlignment="Left" Margin="12,59,0,0" Name="listBox1" VerticalAlignment="Top" Width="279" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="12,30,0,0" Name="textBox1" VerticalAlignment="Top" Width="279" />
</Grid>
答案 0 :(得分:1)
问题是您正在添加空字符串。只需在messagebox之后返回。
private void button1_Click(object sender, RoutedEventArgs e)
{
if (textBox1.Text.Trim() =="")
{
MessageBox.Show("Campul este liber!");
return;
}
//ListBox li = sender as ListBox;
ListBoxItem li = new ListBoxItem();
li.Content=textBox1.Text;
textBox1.Clear();
listBox1.Items.Add(li);
textBox1.Focus();
}
答案 1 :(得分:0)
private void button1_Click(object sender, RoutedEventArgs e)
{
if (textBox1.Text=="")
{
MessageBox.Show("Campul este liber!");
}else{
//ListBox li = sender as ListBox;
ListBoxItem li = new ListBoxItem();
li.Content=textBox1.Text;
textBox1.Clear();
listBox1.Items.Add(li);
textBox1.Focus();
}
}
答案 2 :(得分:0)
您的代码存在一些问题。
克服这两个问题。改变这个
if (textBox1.Text=="")
{
MessageBox.Show("Campul este liber!");
}
到
if (string.IsNullorWhiteSpace(textBox1.Text))
{
MessageBox.Show("Campul este liber!");
return;
}