将WPF combobox ItemsSource绑定到字符串数组时发生错误

时间:2021-10-27 17:06:15

I could not set a combobox's ItemsSource to an Array. I have tried setting the DataContext to the class where the Array is found, and then setting the bindings in XAML

我无法将combobox的ItemsSource设置为数组。我尝试将DataContext设置为找到数组的类,然后在XAML中设置绑定

 class Car
{
    public string[] makes;
}

...

public MainWindow()
{
    Car _Car = new Car();
    _Car.makes = new string[]
        {
            "Toyota",
            "Mitsubishi",
            "Audi",
            "BMW"           
        };

    this.DataContext = _Car;
}

and then in XAML

然后在XAML

<ComboBox Name="cars" Grid.Column="0" 
              Grid.Row="0" Margin="5" 
              ItemsSource="{Binding Path=makes}"/>

It doesn't seem to do anything. My cars combobox won't have any items.

它似乎什么都不起作用。我的车子不会有任何东西。

I've also tried explicitly assigning

我还尝试了显式赋值

cars.ItemsSource= new string[]{
                "Toyota",
                "Mitsubishi",
                "Audi",
                "BMW"           
            };

But then I get this error message:

然后我得到了这个错误信息:

Exception has been thrown by the target of an invocation.

被调用的目标抛出异常。

Is there anything I missed?

我漏掉了什么吗?

2 个解决方案

#1


5  

WPF binding doesn't support fields. Make it a property that has a getter and setter

WPF绑定不支持字段。使它成为具有getter和setter的属性

class Car
{
    public string[] makes { get; set; }
}

Regardless, you do not have to explicitly state Path, so this should suffice

无论如何,您不必显式地声明路径,因此这应该足够了

<ComboBox Name="cars" Grid.Column="0" 
          Grid.Row="0" Margin="5" 
          ItemsSource="{Binding makes}"/>

#2


2  

In Order for data binding to work correctly, you need a 'Property' to bind to.

为了使数据绑定正确工作,需要绑定一个“属性”。

XAML

XAML

<ComboBox Name="cars" Grid.Column="0" 
          Grid.Row="0" Margin="5" 
          ItemsSource="{Binding makes}"/>

Code

代码

class Car
{
    public string[] makes { get; set; }
}

#1


5  

WPF binding doesn't support fields. Make it a property that has a getter and setter

WPF绑定不支持字段。使它成为具有getter和setter的属性

class Car
{
    public string[] makes { get; set; }
}

Regardless, you do not have to explicitly state Path, so this should suffice

无论如何,您不必显式地声明路径,因此这应该足够了

<ComboBox Name="cars" Grid.Column="0" 
          Grid.Row="0" Margin="5" 
          ItemsSource="{Binding makes}"/>

#2


2  

In Order for data binding to work correctly, you need a 'Property' to bind to.

为了使数据绑定正确工作,需要绑定一个“属性”。

XAML

XAML

<ComboBox Name="cars" Grid.Column="0" 
          Grid.Row="0" Margin="5" 
          ItemsSource="{Binding makes}"/>

Code

代码

class Car
{
    public string[] makes { get; set; }
}