【问题标题】:Binding data of multiple classes to single list view/xamarin forms将多个类的数据绑定到单个列表视图/xamarin 表单
【发布时间】:2018-11-10 02:42:08
【问题描述】:

您好,我如何通过 xaml 将多个类的数据绑定到单个列表视图。我成功地将数据从单个类绑定到 lisview,但是当我尝试绑定多个类的数据时,它在 xaml 中没有显示任何内容。

【问题讨论】:

  • 您能否提供来自 xaml 的 sn-p 和您尝试绑定到的 ViewModel?

标签: xaml xamarin data-binding portable-class-library shared-project


【解决方案1】:

您不能“直接”这样做。 由于所有UIElement 控件只有一个BindingContext 属性,因此您一次只能绑定一个对象。

在 MVVM 模式中,您实现 ViewModel 类来分组所有需要的数据以显示在相关页面上...

因此,对于您的“列表视图”,我建议您在 ViewModel 中创建一个属性,该属性引用一个新对象,该对象只是您想要连接到列表视图的所有类的 aggregation

一个简单的例子:

/// Data A needed for your listview 
public class DataA { ... }

/// Data B needed for your listview 
public class DataB { ... }

///
/// You will make a property of this type into your viewModel
///
public class ListviewAggregatedData : INotifyPropertyChanged
{
    private DataA _listviewDataPart1;
    private DataB _listviewDataPart2;

    public DataA ListViewDataPart1
    {
        get => _listviewDataPart1;
        set {  _listviewDataPart1 = value; PropertyChanged?.Invoke(...); }
    }

    public DataA ListViewDataPart2
    {
        get => _listviewDataPart2;
        set {  _listviewDataPart2 = value; PropertyChanged?.Invoke(...); }
    }

    // ....
}

并且在您的 xaml 中,假设您的 viewModel 实现了一个名为“VmAggregatedDataProp”的 ListviewAggregatedData 类型的属性,您可以有这样的东西:

        <ListView
            BindingContext="{Binding VmAggregatedDataProp}"
            Header="{Binding ListViewDataPart1.Title}"
            ItemsSource="{Binding ListViewDataPart2.AllMyItems}"
            />

此示例中的绑定名称必须替换为您自己的属性... 告诉我是否清楚...

【讨论】:

  • 你就在这里 但我的意思是我通过 xml 获取数据并将其存储在共享项目的类中,我通过 viewmodel 访问这些数据,我无法访问 B 类我的 xaml 中的共享项目。
  • 我正在为我的类使用共享项目来获取、设置数据,现在我正在通过视图模型从我的一个共享类中获取数据。但我无法显示来自其他类共享项目的数据,我正在使用 MVVM 方法。
猜你喜欢
  • 2015-04-22
  • 2019-08-17
  • 2023-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-21
相关资源
最近更新 更多