1

CashFlowView、CashFlowViewModel、CashFlowModel の 3 つのクラスのみを使用して、単純な MVVM を作成しました。

インフラジスティックの 9.1 XamDataPresenter (または xamDataGrid) を使用します。

    <igDP:XamDataPresenter Name="xamDataPresenter1" DataSource="{Binding Source={StaticResource CashFlowData}}">

    <ObjectDataProvider x:Key="CashFlowData" ObjectType="{x:Type ViewModel:CashflowViewModel}" MethodName="GetCashFlows" />

私のViewModel内:

public ObservableCollection<CashflowModel> GetCashFlows()
        {
            return new ObservableCollection<CashflowModel>() { ... };
        }

ViewModel は、次の方法で View に接続されます。

this.DataContext = new CashflowViewModel();

グリッドを ObjectDataProvider に接続している限り、完全に正常に動作します。しかし、代わりに ViewModel 内のプロパティに接続できたらいいのにと思いました。

Infragistics によると、私がしなければならないのはこれだけです。

<igDP:XamDataGrid DataSource="{Binding Path=ViewModelCollection}"/>

しかし、この場合、グリッド内の行を表すために、別の ViewModel のコレクションにバインドする必要があるようです。そして、それが私が混乱するところです。

私はこれを試しましたが、うまくいきません:

<igDP:XamDataPresenter Name="xamDataPresenter1" DataSource="{Binding Path=CashFlows}">

ViewModel の内部:

public ObservableCollection<CashflowDataGridViewModel> CashFlows
        {
            get
            {
                return new ObservableCollection<CashflowDataGridViewModel>();
            }
        }

しかし、どうすれば 2 番目の ViewModel (CashflowDataGridViewModel) を作成できますか?

この2番目のViewModel内にこのプロパティを追加しようとしました:

public CashflowModel CashFlow
        {
            get
            {
                return new CashflowModel() {...};
            }
        }

しかし、私のビューに表示されるのは、実際のキャッシュフローモデルクラスの基になるヘッダーがない「キャッシュフロー」列ヘッダーだけです。

4

1 に答える 1

1

View を ViewModel のプロパティにバインドできるようにするには、DataContext を ViewModel のインスタンスに設定する必要があります。私がよく行うのは、View のコード ビハインドのコンストラクターに次の行を含めることです。

this.DataContext = new SomeAwesomeViewModel();

コントロールの異なるグループで異なる ViewModel を使用する場合は、コンテナーの DataContext を設定することもできます (例: Grid.DataContext、StackPanel.DataContext など)。

DataContext を設定したら、その ViewModel のプロパティにバインドできるようになります。

アップデート

以下に、簡単に使用できるサンプル コードを示します。

public class CashFlowViewModel
{
    public ObservableCollection<FlowViewModel> DataGridData
    {
        get...
    }
}

これは、DataGrid にデータを提供するプロパティです。さて、FlowViewModelクラスは次のようになります。

public class FlowViewModel
{
    decimal flowAmount;
    public decimal FlowAmount
    {
        get { return flowAmount; }
        set
        {
            if(flowAmount == value)
                return;

            flowAmount = value;
            NotifyPropertyChanged("FlowAmount");
        }
    }
    .
    .
    .

    private void NotifyPropertyChanged(string propertyName)
    {
        if(PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}
于 2010-06-30T16:09:21.127 に答える