我创建了一个简单的MVVM,只有三个类CashFlowView,CashFlowViewModel,CashFlowModel。

我使用Indragistic的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通过以下方式连接到视图:

this.DataContext = new CashflowViewModel();

只要我将网格连接到ObjectDataProvider,它的运行良好即可。但是我希望我可以将其连接到ViewModel中的属性。

根据侵犯,我要做的就是这样:

<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>();
            }
        }

但是如何创建第二个ViewModel(CashFlowDatagridViewModel)?

我尝试在第二个ViewModel中添加这个万能:

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

但是我在视图上显示的只是“现金流”列标题,而没有实际CashFlowModel类的任何基础标题。

有帮助吗?

解决方案

为了能够将视图绑定到ViewModel上的属性,需要将DataContext设置为您的ViewModel实例。我通常要做的是在我看来的代码构造函数中包括以下行:

this.DataContext = new SomeAwesomeViewModel();

如果您希望不同的控件组使用不同的ViewModels(例如Grid.DataContext,StackPanel.DataContext等),则还可以设置容器的数据台面。

拥有DataContext集后,您应该能够绑定到该ViewModel的属性。

更新

这是一些示例代码,可以让您前进。

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

这就是应该为数据杂志提供数据的属性。现在,这就是 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));
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top