如何在每次按钮点击事件后添加新的并将之前的项目保留在通用列表中?

时间:2017-08-17 08:03:42

标签: c# wpf binding listbox generic-list

我想在用户点击按钮时将新项目添加到我的通用列表中,但是当我单击按钮时,我认为该列表仅包含最后引入的项目。 似乎在每个按钮点击列表中重新初始化。 如何保留旧项目并将新项目添加到我的通用列表中并在列表框中显示所有项目?

谢谢..

C#代码

namespace Example
{
   /// <summary>
   /// Interaction logic for CreateProduct.xaml
   /// </summary>
   public partial class CreateProduct : Window
   {
       public static float weight;
       public static int quantity;
       public static string customer, piece, material;

       public CreateProduct()
       {
            InitializeComponent();

       }

       public static List<Liste> AddList()
       {
            List<Liste> list = new List<Liste>();
            Liste kayit= new Liste();

            kayit.Customer = customer;
            kayit.Piece = piece;
            kayit.Material = material;
            kayit.Quantity = quantity;
            kayit.Weight = weight;

            list.Add(kayit);

            return list;        
       }

       private void btnAdd_Click(object sender, RoutedEventArgs e)
       {
            customer = btnEditCustomer1.Text;
            piece = btnPiece.Text;
            material = txtMaterial.Text;
            quantity = Convert.ToInt32(txtQuantity.Text);
            weight = float.Parse(txtWeight.Text);

            if (customer != null && piece != null && material != null)
            {
                listBoxProduct.ItemsSource = AddList();
            }
        }
    }

    public class Liste
    {
        public string Customer { get; set; }
        public string Piece { get; set; }
        public string Material { get; set; }
        public int Quantity { get; set; }
        public float Weight { get; set; }
    }    
}

XAML代码

<ListBox Grid.Row="1" x:Name="listBoxProduct"  SelectionMode="Single"   Margin="0" Background="Transparent" ScrollViewer.VerticalScrollBarVisibility="Auto"  ScrollViewer.HorizontalScrollBarVisibility="Hidden" Height="200">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Border BorderThickness="1" Margin="0" Height="30" CornerRadius="4" Width="875"  Background="#2E323B" BorderBrush="Black">
                <DockPanel>
                    <TextBlock Text="{Binding Customer}"  Foreground="White" TextWrapping="Wrap"  VerticalAlignment="Stretch" FontSize="16"  HorizontalAlignment="Left" Margin="4,0,0,0"/>
                    <TextBlock Text="{Binding Piece}"    Foreground="White"  TextWrapping="Wrap" VerticalAlignment="Stretch" FontSize="16"  HorizontalAlignment="Left" Margin="4,0,0,0"/>
                    <TextBlock Text="{Binding Material}"  Foreground="White"  TextWrapping="Wrap" VerticalAlignment="Stretch" FontSize="16"  HorizontalAlignment="Left" Margin="4,0,0,0"/>
                    <TextBlock Text="{Binding Quantity}"  Foreground="White"  TextWrapping="Wrap" VerticalAlignment="Stretch" FontSize="16"  HorizontalAlignment="Left" Margin="4,0,0,0"/>
                    <TextBlock Text="{Binding Weight}"  Foreground="White"  TextWrapping="Wrap" VerticalAlignment="Stretch" FontSize="16"  HorizontalAlignment="Left" Margin="4,0,0,0"/>
                </DockPanel>
            </Border>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

4 个答案:

答案 0 :(得分:2)

修复代码的一些问题:

  • 尽可能避免static
  • 不要在每次点击时创建一个新的List实例,而是丢失以前的项目。在窗口中声明一个字段。
  • listBox需要知道何时添加新项目以显示它们。但List没有报告有关添加/删除的信息。使用ObservableCollection
public partial class CreateProduct : Window
{
    private ObservableCollection<Liste> list = new ObservableCollection<Liste>();    

    public CreateProduct()
    {
        InitializeComponent();
        listBoxProduct.ItemsSource = list;
    }

    private void btnAdd_Click(object sender, RoutedEventArgs e)
    {
       float weight;
       int quantity;
       string customer, piece, material;

       customer = btnEditCustomer1.Text;
       piece = btnPiece.Text;
       material = txtMaterial.Text;
       quantity = Convert.ToInt32(txtQuantity.Text);
       weight = float.Parse(txtWeight.Text);

       if (customer != null && piece != null && material != null)
       {
          Liste kayit = new Liste();

          kayit.Customer = customer;
          kayit.Piece = piece;
          kayit.Material = material;
          kayit.Quantity = quantity;
          kayit.Weight = weight;

          list.Add(kayit);
       }
    }
}

答案 1 :(得分:1)

问题是您的AddList()会在每次点击按钮时创建一个新列表。您必须创建一个新属性,例如:

public  ObservableCollection<Liste> AllItems { get; set; } = new ObservableCollection<Liste>();

然后更改您的AddList()

public static Liste CreateItem()
{
    Liste kayit= new Liste();

    kayit.Customer = customer;
    kayit.Piece = piece;
    kayit.Material = material;
    kayit.Quantity = quantity;
    kayit.Weight = weight;

    return kayit;
}

和您的btnAdd_Click()

private void btnAdd_Click(object sender, RoutedEventArgs e)
{
    customer = btnEditCustomer1.Text;
    piece = btnPiece.Text;
    material = txtMaterial.Text;
    quantity = Convert.ToInt32(txtQuantity.Text);
    weight = float.Parse(txtWeight.Text);

    if (customer != null && piece != null && material != null)
    {
        AllItems.Add( CreateItem() );
    }
}

现在CreateItem()您的旧AddList()将创建一个新项目,此项目将在btnAdd_Click方法中添加到您的收藏中。

编辑:

我错过了要说的是你必须在构造函数中设置ItemSource

public CreateProduct()
{
    InitializeComponent();
    listBoxProduct.ItemsSource = AllItems;
}

SiteNote:

我会更改您的整个btnAdd_Click方法 对此:

private void btnAdd_Click(object sender, RoutedEventArgs e)
{
    string customer = btnEditCustomer1.Text;
    string piece = btnPiece.Text;
    string material = txtMaterial.Text;
    int quantity = Convert.ToInt32(txtQuantity.Text);
    float weight = float.Parse(txtWeight.Text);

    if (customer != null && piece != null && material != null)
    {
        var item = new Liste 
                       {
                           Customer = customer,
                           Piece = piece,
                           Material = material,
                           Quantity = quantity,
                           Weight = weight
                       };

        AllItems.Add(item);
    }
}

答案 2 :(得分:0)

好像你的代码完全搞砸了。无论如何,让我快速解决一下对您有用的问题。

<input type="checkbox" <?php if(in_array(2,$_POST['ans'])) { echo "checked"; } ?> name="ans[]" value="2" class="grp1" onclick="phaseCheck();">
<input type="checkbox" <?php if(in_array(3,$_POST['ans'])) { echo "checked"; } ?>  name="ans[]" value="3" class="grp1" onclick="phaseCheck();">

希望有所帮助。

答案 3 :(得分:0)

在每次单击按钮时,您正在重新创建其中包含单个元素的列表,因为AddList方法重新初始化列表(每次都会创建一个新的List)。该列表需要在AddList方法之外(并在按钮单击事件处理程序之外)创建。在AddList中你应该创建一个项目(Liste),然后将其添加到现有列表中,正如@ Gopichandar的回答所指出的那样。

您可能还想考虑使用列表的(单向)绑定到列表框,而不是在每次单击时重新创建列表框的ItemSource。