简体   繁体   English

将WPF组合框ItemsSource绑定到字符串数组时出错

[英]Error when binding WPF combobox ItemsSource to an Array of Strings

I could not set a combobox's ItemsSource to an Array. 我无法将组合框的ItemsSource设置为数组。 I have tried setting the DataContext to the class where the Array is found, and then setting the bindings in XAML 我尝试将DataContext设置为找到Array的类,然后在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? 我有什么想念的吗?

WPF binding doesn't support fields. WPF绑定不支持字段。 Make it a property that has a getter and setter 使其具有吸气剂和吸气剂的属性

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

Regardless, you do not have to explicitly state Path , so this should suffice 无论如何,您不必显式声明Path ,因此这足以满足要求。

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

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; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM