在MVVM中创建viewmodel

时间:2013-12-06 01:04:36

标签: c# wpf silverlight xaml mvvm

我不知道如何为下面的组合框编写一个viewmodel类。

假设我有两个表:CarsEngineMakers

汽车表:

CarID
CarName
EngineMakerID (Foreign Key)

EngineMakers表:

EngineMakerID
EngineMakerName

现在在组合框中我想在列表中显示name of the EngineMaker。现在当我保存更改时EngineMakerID in Cars表应该更新。如何为上述问题编写viewmodel?

1 个答案:

答案 0 :(得分:1)

你基本上想拥有引用发动机制造商型号的车牌

这也应该有帮助

http://blog.cylewitruk.com/2010/09/wpf-combobox-and-databinding-datacontext-itemssource-displaymemberpath-selecteditem-selectedvalue-selectedvaluepath/

// model

public class Cars
{
    public int CarID {get;set}
    public int CarName {get;set}
    // Foreign key
    public int EngineMakerID { get; set; }

    // Navigation properties
    public virtual EngineMakers  EngineMakers  { get; set; }
}
public class EngineMakers
{
    public int EngineMakerID {get;set}
    public int EngineMakerName {get;set}
    // Navigation properties
    public virtual List<EngineMakers> Courses { get; set; }
}

// ViewModel

  public class MainWindowViewModel : ViewModel
    {

         public ObservableCollection<Cars>  Cars { get; private set; }
         public Cars SelectedSourceCars { get; set; }
    }

//绑定

<ComboBox
    ItemsSource="{Binding Cars, Mode=OneWay}"
    DisplayMemberPath="Name"
    SelectedItem="{Binding SelectedSourceCars}" />