我的 wpf 应用程序中有一个组合框,我需要在其中添加从 0 到 255 的 256 个项目。这看起来很简单,但我担心代码长度。
XAML:
<ComboBox ItemsSource="{Binding ChannelBitLengthList}" SelectedItem="{Binding SelectedChannelBitLengthList, Mode=TwoWay}" SelectedIndex="0" />
View 模型:
public ObservableCollection<string> ChannelBitLengthList
{
get { return _ChannelBitLengthList; }
set
{
_ChannelBitLengthList = value;
OnPropertyChanged("ChannelBitLengthList");
}
}
private string _SelectedChannelBitLengthList;
public string SelectedChannelBitLengthList
{
get { return _SelectedChannelBitLengthList; }
set
{
_SelectedChannelBitLengthList = value;
OnPropertyChanged("SelectedChannelBitLengthList");
}
}
Constructor:
//List of Channels
_ChannelBitLengthList.Add("0");
_ChannelBitLengthList.Add("1");
_ChannelBitLengthList.Add("2");
_ChannelBitLengthList.Add("3");
.......... till .Add("255");
我不想有那么多 .Add()
语句来输入项目。有没有一种更有效的替代方法,我可以在代码长度不长的情况下添加所有这 255 个项目?
最佳答案
由于您要插入最多 255 个项目(而不是 254 个),您将使用:
for(int i=0;i<=255;i++)
{
_ChannelBitLengthList.Add(i.ToString());
}
或者,如果您想使用 LINQ:
ChannelBitLengthList = new ObservableCollection<string>(Enumerable.Range(0, 256).Select(str=>str.ToString()));
关于c# - 如何在 WPF 的 Combobox 中有效地添加多个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13049039/