同じデータを表示する UserControls がいくつかあります。各 UserControl には、表示されるデータのレイアウトが異なります。ContentPresenter は、私のリソースで DataTemplate を使用し、Content を StyleViewModel にバインドすることにより、UserControls のいずれかにバインドできます。各 UserControl は、DataTemplate の DataType で定義されている ViewModel に関連付けられています。特定の UserControl に関連付けられた ViewModel はすべて、StyleViewModel から継承します。UserControls は、SettingsViewModel からデータを取得する必要があります。UserControls がメイン ウィンドウに表示されます。
問題は、SettingsViewModel のデータを UserControls にアクセス可能にする方法がわからないことです。
ContentPresenter を使用して表示されるこれらの UserControls のいずれかのコンストラクターに SettingsViewModel への参照を渡すことは可能ですか?
ContentPresenter を使用せずにデータ (つまり、私の UserControls) の異なるビューを簡単に切り替える別の方法はありますか? その場合、UserControls がデータにアクセスできるようにするにはどうすればよいですか?
以下は、SingleLineViewModel.cs のコードです。
public class SingleLineViewModel : StyleViewModel
{
public SingleLineViewModel() { }
}
他の ViewModel も同様です。これらは基本的に StyleViewModel から継承する空のクラスであるため、SettingsViewModel で StyleViewModel 型の Style プロパティにバインドできます。StyleViewModel も、ViewModelBase から継承する本質的に空のクラスです。
以下は、Resources.xaml のコードです。
<ResourceDictionary <!--other code here-->
xmlns:vm="clr-namespace:MyProject.ViewModel"
<!--other code here-->
<DataTemplate DataType="{x:Type vm:SingleLineViewModel}">
<vw:ucSingleLine/>
</DataTemplate>
<DataTemplate DataType="{x:Type vm:SeparateLinesViewModel}">
<vw:ucSeparateLines/>
</DataTemplate>
<!--other code here-->
</ResourceDictionary>
以下は、SettingsViewModel.cs のコードです。
public class SettingsViewModel : ViewModelBase
{
// other code here
private StyleViewModel _style;
public StyleViewModel Style
{
get { return _style; }
set
{
if (value != _style && value != null)
{
_style = value;
OnPropertyChanged("Style");
}
}
}
// other code here
public SettingsViewModel()
{
_style = new SingleLineViewModel();
}
// other code here
}
以下は、私の MainView.xaml のコードです。
<ContentPresenter Name="MainContent" Content="{Binding SettingsVM.Style}"/>