WPF绑定ComboBox到我的ViewModel

pix*_*xel 5 c# wpf xaml mvvm

我正在尝试将我的ViewModel绑定到我的ComboBox.我有像这样定义的ViewModel类:

class ViewModel
{
    public ViewModel()
    {
        this.Car= "VW";
    }

    public string Car{ get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我在Window_Load中将此ViewModel设置为DataContext,如:

   private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        this.DataContext = new CarModel();
    }
Run Code Online (Sandbox Code Playgroud)

然后在我的xaml中,我这样做将我的ComboBox绑定到此ViewModel.我想在我的ComboBox中默认显示"VW":

        <ComboBox Name="cbCar" SelectedItem="{Binding Car, UpdateSourceTrigger=PropertyChanged}">
            <ComboBoxItem Tag="Mazda">Mazda</ComboBoxItem>
            <ComboBoxItem Tag="VW">VW</ComboBoxItem>
            <ComboBoxItem Tag="Audi">Audi</ComboBoxItem>
        </ComboBox>
Run Code Online (Sandbox Code Playgroud)

我有两个问题:

  1. 如何将组合框中选择的默认值设置为"VW"(一旦表单加载,它应在组合框中显示"VW").
  2. 取而代之的上述XAML中设置ComboBoxItems一样,怎么我把它在我的视图模型,然后在组合框加载这些?

谢谢,

更新:到目前为止,我设法实现这一点,但我在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; }
    }
}
Run Code Online (Sandbox Code Playgroud)

E-B*_*Bat 8

正如你想要实现MVVM一样,如果你开始考虑在你的应用程序中代表Cars的对象,那将会好得多:

    public class ViewModel
    {    
            public Car SelectedCar{ get; set; }
            public IEnumerable<Car> Cars{ 
                get  {
                    var cars = YOUR_DATA_STORE.Cars.ToList();
                    SelectedCar = cars.FirstOrDefault(car=>car.Model == "VW");
                    return cars;
                }
            }
    }

    public class Car 
    {
        public string Model {get;set;}
        public string Make { get; set; }
        public int Year { get; set; }
    }
Run Code Online (Sandbox Code Playgroud)

你的Xaml:

<ComboBox SelectedItem="{Binding SelectedCar}", ItemsSource="{Binding Cars}" 
        UpdateSourceTrigger=PropertyChanged}"/>
Run Code Online (Sandbox Code Playgroud)


FUR*_*10N 5

  1. 默认值:如果设置viewModel.Car = "VW",则它将在组合框中自动选择该项目。为此,您需要在INotifyPropertyChanged设置Car之前实施或设置DataContext

INotifyPropertyChanged实现可能类似于:

class ViewModel : INotifyPropertyChanged
{
    private string car;

    public ViewModel()
    {
        this.Car = "VW";
        this.Cars = new ObservableCollection<string>() { "Mazda", "VW", "Audi" };
    }

    public string Car
    {
        get
        {
            return this.car;
        }
        set
        {
            if (this.car != value)
            {
                this.car = value;
                OnPropertyChanged();
            }
        }
    }

    public ObservableCollection<string> Cars { get; }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}
Run Code Online (Sandbox Code Playgroud)

2.绑定ItemsSourceSelectedItem

<ComboBox ItemsSource="{Binding Cars}"
          SelectedItem="{Binding Car, Mode=TwoWay}">
</ComboBox>
Run Code Online (Sandbox Code Playgroud)

您还可以设置ComboBox.ItemTemplate源或视图是否比仅显示字符串更复杂:

    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding}" />
        </DataTemplate>
    </ComboBox.ItemTemplate>
Run Code Online (Sandbox Code Playgroud)

在视图模型中,只需添加一个list属性:

public ObservableCollection<string> Cars { get; set; }
Run Code Online (Sandbox Code Playgroud)

它不是必须的,ObservableCollection但是只要您更改集合,该类型就会自动更新UI。