[英]adding items to a listbox from another wpf window
所以我有我的主窗口,其中包含一個列表框menu_listbox
和一個按鈕Add_menu_item
,當點擊后打開第二個WPF窗口New_menu_item
中,我有texboxes和一個按鈕Add_new_menu_item
當butoon被點擊它將關閉New_menu_item
窗口和值添加到當我嘗試添加新項目時,類為new_listbox_item
,所有以前的項目都更新為添加的新項目。 代碼使用如下
private void add_menu_item_Click(object sender, RoutedEventArgs e)
{
new_menu_item form1 = new new_menu_item();
form1.ShowDialog();
new_listbox_item M_item = new new_listbox_item();
M_item.new_item_name = form1.new_food.Text;
M_item.price = double.Parse(form1.food_price.Text);
M_item.vegitarian = form1.is_vegetarian.IsChecked == true;
menu_Listbox.Items.Add(M_item);
}
有沒有人對如何解決這個問題有任何想法? new_listbox_item
如下所示:
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MainServerWIndow
{
public class new_listbox_item
{
private static string _item_name;
private static Boolean _vegitarian;
private static double _price;
private static double _total;
private double N_price;
public string new_item_name
{
get
{
return _item_name;
}
set
{
_item_name = value;
}
}
public Boolean vegitarian
{
get
{
return _vegitarian;
}
set
{
_vegitarian = value;
}
}
public double price
{
get
{
return _price;
}
set
{
_price = value;
}
}
public static string item_name
{
get
{
return _item_name;
}
set
{
_item_name = value;
}
}
public static double item_price
{
get
{
return _price;
}
set
{
_price = value;
}
}
public static Boolean vegetarian
{
get
{
return _vegitarian;
}
set
{
_vegitarian = value;
}
}
public static double total
{
get
{
return _total;
}
set
{
_total = value;
}
}
public override string ToString()
{
return string.Format("{0} {1} {2}", new_item_name, vegitarian, price);
}
}
}
所有先前的項目都更新為添加的新項目
沒有可靠,可靠地重現問題的良好, 最少 , 完整的代碼示例 ,就無法確定問題的根源。 但是考慮到您發布的代碼,肯定有一個嚴重的代碼缺陷可以解釋您的問題。 您已將類中除一個字段以外的所有字段聲明為static
:
public class new_listbox_item
{
private static string _item_name;
private static Boolean _vegitarian;
private static double _price;
private static double _total;
...
}
這樣,您導致new_listbox_item
類的每個實例共享字段。 在一個實例中設置字段會導致其他所有實例使用新值; 每個實例都沒有自己的字段本地副本。
從所有這些字段中刪除static
關鍵字,這可能會使您的代碼按您希望的方式工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.