【发布时间】:2017-12-19 17:24:28
【问题描述】:
我需要在 UWP 中挖掘一个嵌套的 observable 集合,其中包含另一个 observable 集合,然后将其绑定到我的 XAML。
我该怎么做?
【问题讨论】:
我需要在 UWP 中挖掘一个嵌套的 observable 集合,其中包含另一个 observable 集合,然后将其绑定到我的 XAML。
我该怎么做?
【问题讨论】:
Allen Rufolo 的解决方案有效。但这是解决此问题的另一种方法。
x:Bind 是新实现的,可用于 UWP。我的答案基于 x:Bind
示例类
public class MainItems
{
public string ItemName { get; set; }
public ObservableCollection<SubItems> SubItemsList { get; set; }
}
public class SubItems
{
public string SubItemName { get; set; }
}
样本数据
ObservableCollection<MainItems> _data = new ObservableCollection<MainItems>();
for (int i = 1; i <= 5; i++)
{
MainItems _mainItems = new MainItems();
_mainItems.ItemName = "Main" + i.ToString();
_mainItems.SubItemsList = new ObservableCollection<SubItems>();
for (int j = 1; j <= 3; j++)
{
SubItems _subItems = new SubItems()
{
SubItemName = "SubItem" + i.ToString()
};
_mainItems.SubItemsList.Add(_subItems);
}
_data.Add(_mainItems);
}
我的 XAML
<ListView x:Name="MyMainList">
<ListView.ItemTemplate>
<DataTemplate x:DataType="local:MainItems">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<TextBlock Text="{x:Bind ItemName}" />
<ListView ItemsSource="{x:Bind SubItemsList}" Grid.Row="1">
<ListView.ItemTemplate>
<DataTemplate x:DataType="local:SubItems">
<TextBlock Foreground="Red" Text="{x:Bind SubItemName}"/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
x:Bind 为您提供了一种绑定嵌套 Observable 集合的简单方法
输出
【讨论】:
ListViewItem 在左侧有默认的 12px 边距。因此,如果您想删除它,您可以重新模板 ListViewItem 或在第二个 DataTemplate 上添加 Margin="-12,0,0,0"
你的可观察集合的代码示例会有所帮助,但你可以做这样的事情......
public class MyViewModel
{
public ObservableCollection<MyObject> MyObjectCollection { get; set;}
}
public class MyObject
{
public string ObjectName {get; set;}
public ObservableCollection<AnotherObject> AnotherObjectCollection { get; set; }
}
在您的 XAML 中,您可以绑定到与此类似的这些集合
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<ListView x:Name="ListView1" Grid.Column="0"
ItemsSource="{Binding MyObjectCollection}">
<ListView.ItemTemplate>
<Datatemplate>
<TextBlock Text="{Binding ObjectName}"/>
</Datatemplate
</ListView.ItemTemplate>
</ListView>
<Grid Grid.Column=1 DataContext="{Binding ElementName=ListView1, Path=SelectedItem}">
<ListView ItemsSource="{Binding AnotherObjectCollection}"/>
</Grid>
</Grid>
在此示例中,第二个 Grid 的 DataContext 绑定到 ListView1 中的选定项。
【讨论】:
【讨论】: