c# - 如何在 WPF 的 Combobox 中有效地添加多个项目

标签 c# .net wpf mvvm combobox

我的 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/

相关文章:

c# - 如何避免使用 C# 在 MongoDB 中重复插入而不使用 "_id"键?

c# - 机器人框架 V4 : Question about Input forms cards

WPF + 多个应用程序实例之间的通信

c# - 比较来自另一类C#的属性上的属性引用

c# - 为什么十进制类不使用剩余的 26 位?

c# - .NET try/catch 便宜吗?

c# - 点混淆器(.NET 混淆器)是否会在未安装混淆器的机器上引起问题?

c# - 委托(delegate)和事件之间的关系是什么?

wpf - 在 wpf 中将图像放入 ViewPort3D

c# - 从全局X关闭按钮调用viewModel中定义的方法