使用C#WPF在组合框中添加项目

时间:2018-11-30 21:57:20

标签: c# wpf combobox

我正在使用C#WPF。你好

我不能在组合框中添加项目。该错误的大多数名称是“ MyList1”的“ System.NullReferenceException”。 我设法生成了所需的组合框,但是当我想将数据放入其中一个组合框时,我不知道该怎么做。 这是我的代码,其中包含我测试过的将项目添加到组合框但没有任何作用的代码:

namespace GenDet
{

    public partial class NewDetail : Page
    {
        List<String> MyElements = new List<String>();
        ComboBox[] MyList1 = new ComboBox[3];
        private object item;
        public NewDetail()
        {
            InitializeComponent();
        }
        private void OnClick1(object sender, RoutedEventArgs e)
        {
            string MyValue = MyList.SelectedValue.ToString();
            if (MyElements.Count == 3)
            {
                MessageBox.Show("Number max of elements reached", "Alert", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            else
            {
                AddList(MyValue, MyElements);
            }
        }
        private void AddList (string MyValue, List<string> MyElements)
        {
            int Nbe = MyElements.Count;
            if (Nbe == 0 || (MyElements[Nbe-1] != MyValue && (MyElements[Nbe-1] == "Mur" || MyValue == "Mur"))) 
            {
                //List<string> MyLittleList = new List<string>();
                //MyLittleList.Add("Coucou");
                MyElements.Add(MyValue);

                //Dictionary<string, string> test = new Dictionary<string, string>();
                //test.Add("1", "Item 1");
                //test.Add("2", "Item 2");
                //test.Add("3", "Item 3");
                //MyList1[].
                //MyList1[Nbe].Items.Add("Item 1");
                //MyList1[Nbe].DisplayMemberPath = "Key";
                //MyList1[Nbe].SelectedValuePath = "Value";
                //MyList1[Nbe].Items.Add(new KeyValuePair<string, string>("2", "Item 2"));
                //MyList1[Nbe].Items.Add(new KeyValuePair<string, string>("3", "Item 3"));

                //public ObservableCollection<string> MyLittleList= new ObservableCollection<string>();

                //string[] str = new string[] { "Item 1", "Item 2" };
                //MyList1[Nbe].ItemsSource = str;
                //MyList1[Nbe].SelectedIndex = 0;



                MyPage.Children.Add(MyList1[Nbe]);
                //MyList1[Nbe].Resources = MyLittleList;
                MyList1[Nbe].Height = 30;
                MyList1[Nbe].Width = 120;
                MyList1[Nbe].HorizontalAlignment = HorizontalAlignment.Left;
                MyList1[Nbe].VerticalAlignment = VerticalAlignment.Top;
                MyList1[Nbe].Margin = new Thickness(40 + (Nbe * 250), 110, 0, 0);
            } 
        }
    }
}

谢谢!

0 个答案:

没有答案