[英]How do I turn a listbox into a string array in c# wpf?
I'm working on a project where I have to pass a receipt between windows, how would i turn the listbox into a string array to pass it to another window?我正在做一个项目,我必须在 windows 之间传递收据,我如何将列表框转换为字符串数组以将其传递给另一个 window? Or is there an easier way to do that?或者有没有更简单的方法来做到这一点?
For your description, you want to convert your listbox to a string array and pass it to another window.对于您的描述,您希望将列表框转换为字符串数组并将其传递给另一个 window。
You can try the following code.你可以试试下面的代码。
MainWindow:主窗口:
public MainWindow()
{
InitializeComponent();
listBox1.Items.Add("Mon");
listBox1.Items.Add("Tue");
listBox1.Items.Add("Wed");
listBox1.Items.Add("Thu");
listBox1.Items.Add("Fri");
}
public string[] result { get; set; }
private void btntest_Click(object sender, RoutedEventArgs e)
{
List<string> list = new List<string>();
foreach (string item in listBox1.Items)
{
list.Add(item);
}
result = list.ToArray();
Window1 window = new Window1();
window.Show();
}
Window1:窗口1:
public Window1()
{
InitializeComponent();
listBox2.ItemsSource = ((MainWindow)Application.Current.MainWindow).result;
}
Lets say you have a WPF Listbox like this假设您有一个像这样的 WPF 列表框
<ListBox Name="listBox1" HorizontalAlignment="Left" VerticalAlignment="Top" Width="194" Height="200">
<ListBoxItem Content="aa"></ListBoxItem>
<ListBoxItem Content="bb"></ListBoxItem>
<ListBoxItem Content="cc"></ListBoxItem>
<ListBoxItem Content="dd"></ListBoxItem>
<ListBoxItem Content="ee"></ListBoxItem>
<ListBoxItem Content="ff"/>
</ListBox>
You can get the items in string[] using Linq as follows您可以使用 Linq 获取字符串 [] 中的项目,如下所示
ItemCollection i1 = listBox1.Items;
string[] s1 = i1.Cast<ListBoxItem>().Select(x => (string)x.Content).ToArray();
That's it.而已。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.