如何删除空白区域

时间:2014-04-12 09:33:47

标签: c# wpf xaml

我有一个简单的清单;一切正常,但是当我单击按钮并且列表为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>

http://i59.tinypic.com/den49d.png

3 个答案:

答案 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)

您的代码存在一些问题。

  1. 您只是检查用户是否输入了任何内容。如果他进入空间怎么办?对于此用途String.IsNullorWhiteSpace
  2. 显示消息框后您没有返回。为此,您需要在显示消息框后返回。
  3. 克服这两个问题。改变这个

    if (textBox1.Text=="")
    {
         MessageBox.Show("Campul este liber!");    
    }
    

    if (string.IsNullorWhiteSpace(textBox1.Text))
    {
          MessageBox.Show("Campul este liber!");
          return;
    }