将 WPF 组合框 ItemsSource 绑定到字符串数组时出错
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20343706/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Error when binding WPF combobox ItemsSource to an Array of Strings
提问by Carl Nathan Mier
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
我无法将组合框的 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;
}
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?
有什么我错过的吗?
回答by Omri Btian
WPF binding doesn't support fields. Make it a property that has a getter and setter
WPF 绑定不支持字段。使其成为具有 getter 和 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}"/>
回答by Ramashankar
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; }
}

