【问题标题】:UWP best way to use x:Bind and filter ObservableCollectionUWP 使用 x:Bind 和过滤 ObservableCollection 的最佳方式
【发布时间】:2018-05-27 10:17:31
【问题描述】:

我有一个 UWP 应用程序。

一个带有 pivot 控件的视图。

一个关联的 ViewModel。

一个这样的模型:

class Model
{
    public int Category { get; set; }
}

在 ViewModel 中,有一个模型“模型”的 ObservableCollection,例如:

public ObservableCollection<Model> models = new ObservableCollection<Model>();

我想在数据透视控件中显示模型,每个模型按类别在数据透视项中。例如,PivotItem 1 将计入类别 1 的所有模型,PivotItem 2 将计入类别 2 的所有模型,等等...

一种解决方案是为按类别过滤的每个模型创建新的 ObservableCollection,但我认为这个解决方案仍然有点繁重。例如:

public ObservableCollection<Model> modelCategory1 = models.Where(x => x.category == 1) [...]

这就是为什么我想知道是否没有直接从 XAML 过滤的解决方案。

编辑:

在他看来,在 Pivot 中,我有 5 个数据透视项,每个都包含一个 ListView

<Pivot>
    <PivotItem>
        <ListView ItemsSource="{x:Bind ViewModel.Models}" />
    </PivotItem>
    <PivotItem>
        <ListView ItemsSource="{x:Bind ViewModel.Models}" />
    </PivotItem>
    <PivotItem>
        <ListView ItemsSource="{x:Bind ViewModel.Models}" />
    </PivotItem>
    <PivotItem>
        <ListView ItemsSource="{x:Bind ViewModel.Models}" />
    </PivotItem>
    <PivotItem>
        <ListView ItemsSource="{x:Bind ViewModel.Models}" />
    </PivotItem>
</Pivot>

编辑 2:

根据 Can I filter a collection from xaml?[UWP]CollectionViewSource Filter? 我无法从 UWP 的 CollectionViewSource 中过滤,所以我想我必须创建新的 ObservableCollection 来包含过滤结果,例如:

private ObservableCollection<Model> _modelsCategory1; 
public ObservableCollection<Model> ModelsCategory1
{ 
    get { return _modelsCategory1; } 
    set { _modelsCategory1= value; NotifyPropertyChanged(); 
} 

和:

var cat1 = from fobjs in Models 
         where fobjs.Category == 1 
         select fobjs;
ModelsCategory1  = new ObservableCollection<Model>(cat1);

【问题讨论】:

  • 如果您使用数据绑定,您将需要模型类中的另一个属性来绑定数据透视表头。
  • 我已编辑显示 UI 部分

标签: c# xaml mvvm uwp observablecollection


【解决方案1】:

在现有代码中执行此操作以将 Category 属性绑定到 ListViewItem,

<PivotItem>
    <ListView ItemsSource="{x:Bind ViewModel.Models}">
        <ListView.ItemTemplate>
            <DataTemplate x:DataType="data:Model">
                <TextBlock Text="{x:Bind Category}"/>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</PivotItem>

【讨论】:

  • 这将显示我列表中的所有类别,我的问题是根据每个 PivotItem 中的类别在 ViewModel.Models 中显示成员:第一个 PivotItem 将仅显示与“ViewModel.Models where category == 1”,第二个 PivotItem 将仅显示与“ViewModel.Models where category == 2”匹配的模型,等等...
猜你喜欢
  • 2017-08-06
  • 1970-01-01
  • 2016-03-05
  • 2019-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-11
  • 2013-09-18
相关资源
最近更新 更多