次のパターンに従います。
この部分は、モデル クラスがどのように見えるかです。エンティティ フレームワークを使用してモデルを作成する場合でも、モデルは INPC を継承します。すべて問題ありません。
public class Model_A : INotifyPropertyChanged
{
// list of properties...
public string FirstName {get; set;}
public string LastName {get; set;}
// etc...
}
各ビュー モデルは表示される情報のサブセットであるため、同じモデル クラスに対して多くのビュー モデルを使用できます。パラメーターなしの c-tor を呼び出す場合は、モック モデルの自動インスタンスを取得することに注意してください。ビューモデルで使用されます。
public class ViewModel_A1 : INotifyPropertyChanged
{
public Model_A instance;
public ViewModel()
{
instance = new instance
{ //your mock value for the properties..
FirstName = "Offer",
LastName = "Somthing"
};
}
public ViewModel(Model_A instance)
{
this.instance = instance;
}
}
これはビュー用です。ide デザイナーで表示すると、モック ビュー モデルが表示されます。
public class View_For_ViewModelA1
{
public View_For_ViewModel_A1()
{
//this is the generated constructor already implemented by the ide, just add to it:
DataContext = new ViewModel_A1();
}
public View_For_ViewModel_A1(ViewModel_A1 vm)
{
DataContext = vm;
}
}
XAML 側:
<Window x:Class="WpfApplication1.View_For_ViewModel_A1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:ViewModel="clr-namespace:WpfApplication1"
mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300"
d:DataContext="{d:DesignInstance ViewModel:ViewModel_A1, IsDesignTimeCreatable=True}"
Title="Window1" Height="300" Width="300">
<Grid>
<TextBox Text="{Binding FirstName}" />
<TextBox Text="{Binding LastName}" />
</Grid>
</Window>
より高度なシナリオでは、単一のビュー モデル クラスを複数のモデル クラスに関連付ける必要がありますが、常に単一のビュー モデルにバインドするようにビューを設定する必要があります。コードでカンフーが必要な場合は、ビューモデルレイヤーでそれを行うようにしてください。(つまり、異なるモデル タイプの複数のインスタンスを持つビュー モデルを作成する)
注: これは mvvm の完全なパターンではありません。完全なパターンでは、ビューモデルを介してモデル内のメソッドに関連し、ビューにもバインド可能なコマンドを公開できます。幸運を :)