我正在尝试将我的ViewModel与ComboBox绑定。 我定义的ViewModel类如下:
class ViewModel
{
public ViewModel()
{
this.Car= "VW";
}
public string Car{ get; set; }
}
我在Window_Load中将这个ViewModel设置为DataContext:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
this.DataContext = new CarModel();
}
然后在我的XAML中,我使用以下代码将我的ComboBox绑定到这个ViewModel。我希望“VW”默认显示为我的ComboBox中的选中项:
<ComboBox Name="cbCar" SelectedItem="{Binding Car, UpdateSourceTrigger=PropertyChanged}">
<ComboBoxItem Tag="Mazda">Mazda</ComboBoxItem>
<ComboBoxItem Tag="VW">VW</ComboBoxItem>
<ComboBoxItem Tag="Audi">Audi</ComboBoxItem>
</ComboBox>
我有两个问题:
- 如何将下拉框的默认值设置为“VW”(表单加载后,应在下拉框中显示“VW”)。
- 不是像上面在xaml中设置ComboBoxItems,而是如何在我的ViewModel中设置它们,然后在ComboBox中加载这些内容?
谢谢。
更新: 到目前为止,我已经实现了这一点,但是在ViewModel c-tor中出现了以下错误:
namespace MyData
{
class ViewModel
{
public ViewModel()
{
this.Make = "";
this.Year = 1;
this.DefaultCar = "VW"; //this is where I get error 'No string allowed'
}
public IEnumerable<Car> Cars
{
get
{
var cars = new Car[] { new Car{Model="Mazda"}, new Car{Model="VW"}, new Car{Model="Audi"} };
DefaultCar = cars.FirstOrDefault(car => car.Model == "VW");
}
}
public string Make { get; set; }
public int Year { get; set; }
public Car DefaultCar { get; set; }
}
class Car
{
public string Model { get; set; }
}
}