我无法填充列表框。我最初得到了网站上某人的帮助,但似乎没有完全发挥作用。我试图用文本文件中的项目填充列表框到目前为止的代码:
namespace ACW2
{
/// <summary>
/// Interaction logic for InventoryWindow.xaml
/// </summary>
///
public partial class InventoryWindow : Window
{
public InventoryWindow()
{
InitializeComponent();
categoryComboBox.Items.Add("All");
categoryComboBox.Items.Add("Pizza");
categoryComboBox.Items.Add("Burger");
categoryComboBox.Items.Add("Sundry");
categoryComboBox.SelectedValue = "All";
PopulateList();
}
private void listBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
private void categoryComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
PopulateList();
}
public void PopulateList()
{
listBox.Items.Clear();
using (StreamReader sr = new StreamReader(@"inventory.txt"))
{
while (!sr.EndOfStream)
{
for (int i = 0; i < 22; i++)
{
string StringListItem = sr.ReadLine();
if (!String.IsNullOrEmpty(StringListItem) &&
(categoryComboBox.SelectedItem != null &&
(StringListItem.Contains(categoryComboBox.SelectedItem.ToString()))))
listBox.Items.Add(StringListItem);
}
}
}
}
}
}
它最终只有一个空的列表框。但是,这段代码确实填充了列表框,但我觉得这两个StreamReader好像是多余的:
namespace ACW2
{
/// <summary>
/// Interaction logic for InventoryWindow.xaml
/// </summary>
///
public partial class InventoryWindow : Window
{
public InventoryWindow()
{
InitializeComponent();
categoryComboBox.Items.Add("All");
categoryComboBox.Items.Add("Pizza");
categoryComboBox.Items.Add("Burger");
categoryComboBox.Items.Add("Sundry");
categoryComboBox.SelectedValue = "All";
}
private void listBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
private void categoryComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
listBox.Items.Clear();
StreamReader sr = new StreamReader("inventory.txt");
string i = sr.ReadToEnd();
string[] n = i.Split('\n');
foreach (string s in n)
{
listBox.Items.Add(s);
}
}
public void PopulateList()
{
listBox.Items.Clear();
using (StreamReader sr = new StreamReader(@"inventory.txt"))
{
while (!sr.EndOfStream)
{
for (int i = 0; i < 22; i++)
{
string StringListItem = sr.ReadLine();
if (!String.IsNullOrEmpty(StringListItem) &&
(categoryComboBox.SelectedItem != null &&
(StringListItem.Contains(categoryComboBox.SelectedItem.ToString()))))
listBox.Items.Add(StringListItem);
}
}
}
}
}
}
答案 0 :(得分:0)
foreach (var line = File.ReadAllLines(@"inventory.txt"))
{
listBox.Items.Add(line);
}
答案 1 :(得分:0)
我不是通过代码隐藏来实现这一点,而是设置一个带有项目类型的ObservableCollection的ViewModel(例如字符串或更健壮的东西),并将ComboBox从XAML绑定到该集合属性名称。
通过这种方式,您可以更轻松地维护此应用程序+免费查看分离:)
// SampleViewModel.cs
public ObservableCollection<string> Categories = new ObservableCollection<string>();
// SampleView.xaml
<Window.DataContext>
<local:SampleViewModel/>
</Window.DataContext>
<ListView ItemSource="{Binding Categories}" />
&#13;
这应该这样做:)