2

同じデータを表示する 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}"/>
4

1 に答える 1

0

一度に多くのことをしようとしていることに気付くかもしれません。このシナリオをどのようにテストできるか考えてみてください。または、デバッガーでデータをどのように調べて、その状態を確認しますか? データを UI 要素から分離することをお勧めします。通常、使用しようとしているような MVVM パターンは、データを単純なデータから UI が使用できるフォームに移行するのに役立つビュー モデルを提供します。そのことを念頭に置いて、UI が一緒に保持することなくすべてのデータを表示する ViewModel 層を開発することをお勧めします。つまり、追加の SettingsViewModel をコントロールに挿入しようとする代わりに、ViewModel に必要なものすべてを保持させる必要があります。

良いスタートを切ったようです。SettingsViewModel を使用すると Style を取得できますが、スタイルにはデータがないようです。したがって、コンストラクターで渡してはいけません。

public SettingsViewModel()
{
    _style = new SingleLineViewModel(WhatINeedForStyle);
}
于 2013-01-01T13:25:55.500 に答える