在不同的模型MVVM中使用模型多次

时间:2017-07-11 21:21:10

标签: c# wpf mvvm

我有一个使用Child Model 2x作为其中一个属性的模型。我可以将所有数据正确加载到模型中,但我无法弄清楚如何正确地将其显示到数据网格中。使用测试行我知道它的绑定,但我不能让它显示任何属性。

模型

class BidLine
    {
        public TestProduct CompetitorItem;
        public TestProduct BEItem;


        public ObservableCollection<BidLine> LoadProduct()
        {

            var tList = new ObservableCollection<BidLine>();

            tList.Add(new Model.BidLine
            {
                BEItem = new TestProduct
                {
                    ProductID = "test1",
                    VendorID = "vnd1"
                },

                CompetitorItem = new TestProduct
                {
                    ProductID = "test2",
                    VendorID = "vnd2"
                }
            });

            tList.Add(new Model.BidLine
            {
                BEItem = new TestProduct
                {
                    ProductID = "test1",
                    VendorID = "vnd1"
                },

                CompetitorItem = new TestProduct
                {
                    ProductID = "test2",
                    VendorID = "vnd2"
                }
            });

            return tList;
        }

    }

儿童模特

class TestProduct : ModelBase
{
    private string _productid;
    public string ProductID
    {
        get { return _productid; }
        set
        {
            _productid = value;
            RaisePropertyChanged("ProductID");
        }
    }

    private string _vendorID;
    public string VendorID
    {
        get { return _vendorID; }
        set
        {
            _vendorID = value;
            RaisePropertyChanged("VendorID");
        }
    }
}

查看模型

class ProductViewModel
{
    public ObservableCollection<BidLine> Products { get; set; }

    public ProductViewModel()
    {
        var dl = new BidLine();
        Products = dl.LoadProduct();
    }

编辑:

XAML代码

  <Grid>
<DataGrid ItemsSource="{Binding Path=Products}">
    <DataGrid.Columns>
        <DataGridTextColumn Binding="{Binding Path=BEItem.ProductID}" Header="ProductID"/>
    </DataGrid.Columns>
</DataGrid>

1 个答案:

答案 0 :(得分:1)

绑定不适用于字段。你需要有财产。所以将BEItem和CompetitorItem转换为属性......

    public TestProduct CompetitorItem { get; set; }
    public TestProduct BEItem { get; set; }

事情将开始奏效。调试绑定的最佳方法是观察输出窗口。如果您查看了输出窗口,您会看到这个......

System.Windows.Data Error: 40 : BindingExpression path error: 'BEItem' property not found on 'object' ''BidLine' (HashCode=31093287)'

这清楚地表明当所有存在的东西都是BEItem字段时,绑定引擎正在寻找属性BEItem。

相关问题