gpt4 book ai didi

c# - ObservableCollection (ViewModel) 中的 MVVM ObservableCollection

转载 作者:行者123 更新时间:2023-12-03 10:59:21 25 4
gpt4 key购买 nike

我只是想知道如何拥有父集合的子集合?

例如,

我已经有一个 ObservableCollection 产品,它正在添加并正确绑定(bind)到 XAML。但是,现在我需要另一个包含产品项目的 ObservableCollection。

基本上我正在考虑在 View 模型中拥有类似的东西

 ProductCollection[0].ProductItemCollection.Add(newProductitem);

我将如何在 MVVM 中解决这个问题?

谢谢

克里斯

最佳答案

不确定这是否是您正在寻找的,但...

假设您的 xaml 中有两个网格。第一个显示您的产品,第二个显示所选产品的项目。

<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow"
Height="350"
Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="173*" />
<RowDefinition Height="147*" />
</Grid.RowDefinitions>

<DataGrid ItemsSource="{Binding ProductsCollection}"
SelectedItem="{Binding SelectedProduct}"
Margin="10">
</DataGrid>

<DataGrid ItemsSource="{Binding ProductItemsCollection}"
Margin="10"
Grid.Row="1">
</DataGrid>

</Grid>

你有声明的类
public class Product
{
public Product()
{
ItemsCollection = new ObservableCollection<Item>();
}
public int ID { get; set; }
public string Name { get; set; }
public ObservableCollection<Item> ItemsCollection { get; set; }
}

public class Item
{
public int ID { get; set; }
public DateTime Date { get; set; }
}

从第一个网格中选择一个产品将更新 VM 中第二个网格的 itemsource,如下所示
    private ObservableCollection<Product> _ProductsCollection = new ObservableCollection<Product>();
public ObservableCollection<Product> ProductsCollection
{
get{return _ProductsCollection;}
set
{
_ProductsCollection = value;
OnPropertyChanged("ProductsCollection");
}
}

private ObservableCollection<Item> _ProductItemsCollection;
public ObservableCollection<Item> ProductItemsCollection
{
get {return _ProductItemsCollection; }
set
{
_ProductItemsCollection = value;
OnPropertyChanged("ProductItemsCollection");
}
}

private Product _SelectedProduct = null;
public Product SelectedProduct
{
get {return _SelectedProduct;}
set
{
_SelectedProduct = value;
ProductItemsCollection = _SelectedProduct.ItemsCollection;
OnPropertyChanged("SelectedProduct");
}
}

最后你添加一些示例数据
    public MainWindow()
{
InitializeComponent();
this.DataContext = this;

Product product1 = new Product() { ID = 1, Name = "Product1" };
product1.ItemsCollection.Add(new Item() { ID = 1, Date = DateTime.Now});
product1.ItemsCollection.Add(new Item() { ID = 2, Date = DateTime.Now.AddDays(-1) });

Product product2 = new Product() { ID = 2, Name = "Product2" };
product2.ItemsCollection.Add(new Item() { ID = 3, Date = DateTime.Now });
product2.ItemsCollection.Add(new Item() { ID = 4, Date = DateTime.Now.AddDays(-2) });

ProductsCollection.Add(product1);
ProductsCollection.Add(product2);
}

关于c# - ObservableCollection (ViewModel) 中的 MVVM ObservableCollection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22906799/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com