繁体   English   中英

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

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

我无法将组合框的ItemsSource设置为数组。 我尝试将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;
}

然后在XAML中

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

它似乎什么也没做。 我的汽车组合框没有任何物品。

我也尝试过明确分配

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

但是然后我收到此错误消息:

调用的目标已引发异常。

我有什么想念的吗?

WPF绑定不支持字段。 使其具有吸气剂和吸气剂的属性

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

无论如何,您不必显式声明Path ,因此这足以满足要求。

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

为了使数据绑定正常工作,您需要绑定“属性”。

XAML

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

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

暂无
暂无

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

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