使用数组 C# WPF 中的项目填充列表框
Posted
技术标签:
【中文标题】使用数组 C# WPF 中的项目填充列表框【英文标题】:Populating Listbox with items from an array C# WPF 【发布时间】:2019-06-05 12:05:02 【问题描述】:我在 xaml 文件中创建了一个字符串数组,我需要将其用作 c# wpf ListBox 控件中的项目。我尝试了各种方法从数组中获取项目以添加到 ListBox,但无济于事。这是我的代码:
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<string>DocumentSettings.DepositRuntimeDefaults</string>
<string>DocumentSettings.LendingCustomization.CommonSettings</string>
</ArrayOfString>
这就是数组,现在在我后面的代码中我有一个创建列表的单例:
using System.Collections.Generic;
using System.IO;
namespace csi.Framework.Business
public class UIPathOptionsManager
public static UIPathOptionsManager Instance = new UIPathOptionsManager();
public List<string> UIPathOptions;
public string theUIPathOptionsFile get; set;
public void Initialize(string theDirectory)
theUIPathOptionsFile = theDirectory + "\\UIPathOptions.xaml";
if (File.Exists(theUIPathOptionsFile))
System.Xml.Serialization.XmlSerializer xmlDeserializer = new
System.Xml.Serialization.XmlSerializer(typeof(List<string>));
TextReader fileReader = new StreamReader(theUIPathOptionsFile);
UIPathOptions = (List<string>)xmlDeserializer.Deserialize(fileReader);
fileReader.Close();
然后我有一个需要填充的 ListBox 类:
ListBox theUIPathOptionslistBox = new ListBox();
theUIPathOptionslistBox.Items.Add();
theUIPathOptionslistBox.TabIndex = nRow;
theUIPathOptionslistBox.SelectionMode = SelectionMode.Multiple;
theUIPathOptionslistBox.ClipToBounds = true;
theUIPathOptionslistBox.Focusable = true;
theUIPathOptionslistBox.Visibility = Visibility.Hidden;
theUIPathOptionslistBox.Height = 24;
我真的希望有人可以帮助我 - 感觉我应该知道这一点,但是......
【问题讨论】:
将UIPathOptions
分配给ListBox 的ItemsSource
属性。
【参考方案1】:
将 UIPathOptionsManager.Instance.UIPathOptions 分配给 ItemSource。在 Window_Loaded 事件中执行此操作。
UIPathOptionsManager.Instance.Initialize
(@"C:\Users\Administrator\source\repos\WpfApp9");
ListBox theUIPathOptionslistBox = new ListBox();
theUIPathOptionslistBox.ItemsSource = UIPathOptionsManager.Instance.UIPathOptions;
theUIPathOptionslistBox.TabIndex = nRow;
theUIPathOptionslistBox.SelectionMode = SelectionMode.Multiple;
theUIPathOptionslistBox.ClipToBounds = true;
theUIPathOptionslistBox.Focusable = true;
theUIPathOptionslistBox.Visibility = Visibility.Hidden;
theUIPathOptionslistBox.Height = 24;
您也可以通过创建属性然后使用绑定来做到这一点。
【讨论】:
谢谢 Satish,我已将您的回复标记为答案 - 非常感谢!以上是关于使用数组 C# WPF 中的项目填充列表框的主要内容,如果未能解决你的问题,请参考以下文章