Error when binding WPF combobox ItemsSource to an Array of Strings

最后都变了- 提交于 2019-12-24 06:45:49

问题


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

 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

<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?


回答1:


WPF binding doesn't support fields. 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

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



回答2:


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

XAML

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

Code

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


来源:https://stackoverflow.com/questions/20343706/error-when-binding-wpf-combobox-itemssource-to-an-array-of-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!