1

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?

Omri Btian
  • 6,499
  • 4
  • 39
  • 65
Carl Nathan Mier
  • 51
  • 1
  • 1
  • 7

2 Answers2

7

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}"/>
Omri Btian
  • 6,499
  • 4
  • 39
  • 65
  • wow. it worked, thanks!.. but how could it be, when 'makes' has already been set to 'public', which in my understanding is already accessible by other functions? – Carl Nathan Mier Dec 03 '13 at 06:04
  • 1
    @CarlNathanMier It is accessible, but this is not enough. WPF binding works on the `PropertyDescriptor` model which requires a property. you can read more about it [here](http://stackoverflow.com/questions/842575/why-does-wpf-support-binding-to-properties-of-an-object-but-not-fields) – Omri Btian Dec 03 '13 at 06:06
  • Thanks, but would you also know why assigning 'cars.ItemsSource= new string[]{ "Toyota", "Mitsubishi", "Audi", "BMW" };' returns the exception? thanks – Carl Nathan Mier Dec 03 '13 at 06:29
  • @CarlNathanMier My guess would be that you might set the `ItemsSource` twice, in the xaml `ItemsSource="{Binding makes}"` and in the code-behind, but you should look into the inner exception to get more details ... – Omri Btian Dec 03 '13 at 06:42
3

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; }
}
Ramashankar
  • 1,598
  • 10
  • 14