当错误WPF组合框的ItemsSource绑定到字符串数组 [英] Error when binding WPF combobox ItemsSource to an Array of Strings

查看:116
本文介绍了当错误WPF组合框的ItemsSource绑定到字符串数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不能设置一个组合框的的ItemsSource为数组。我曾尝试在DataContext设置为此处数组中发现的类,然后设置在XAML绑定

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

,然后在XAML

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.

我也试了明确分配

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.

有什么我错过了吗?

推荐答案

WPF绑定不支持领域。使其具有getter和属性setter

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

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

无论如何,你不必明确说明路径,所以这应该足够了。

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

这篇关于当错误WPF组合框的ItemsSource绑定到字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆