【问题标题】:Binding a nested Collection to listview Columns将嵌套集合绑定到列表视图列
【发布时间】:2020-09-17 09:13:34
【问题描述】:

我有一个这样的对象:

public class DummyVm {
    public string Name { get; set; }
    public List<int> DummyList { get; set; }
}

并创建一个 Collection 以将其绑定到视图

public List<DummyVm> VmList { get; set; } = new List<DummyVm>()  { 
    new DummyVm() { Name = "test1", DummyList = new List<int>() { 5, 6 } }, 
    new DummyVm() { Name = "test2", DummyList = new List<int>() { 1, 2 } } 
};

如何将 DummyList-Property 的每个元素绑定到自己的列?

最后,我的结果应该是一个包含 3 列和 2 行的网格:

test1 | 5 | 6
test2 | 1 | 1

我正在使用 mvvm

【问题讨论】:

  • 到目前为止你尝试过什么?如果DummyList 的长度不同,这应该是什么样子?
  • 我尝试像“name”属性一样绑定列表,并希望列表视图会为 DummyList 中的每个属性生成一个列。但没有:)

标签: c# wpf windows mvvm


【解决方案1】:

如果在 MainWindow.xaml.cs 中声明了 VmList,请将其添加到 MainWindow.xaml:

<Window.Resources>

    <DataTemplate x:Key="DummyVmTemplate">

        <StackPanel Orientation="Horizontal">

            <Label FontSize="14" Content="{Binding Name}" />
            <Label Margin="20,0,0,0" Content="{Binding DummyList[0]}" />
            <Label Margin="20,0,0,0" Content="{Binding DummyList[1]}" />

        </StackPanel>
        
    </DataTemplate>
    
</Window.Resources>

在 MainWindow.xaml 中的&lt;Grid&gt; 内添加:

<ListView x:Name="DummyListView"
          ItemTemplate="{StaticResource DummyVmTemplate}" />

然后在 MainWindow.xaml.cs 构造函数中添加:

    Loaded += OnLoaded;

OnLoaded() 实现应该如下所示:

    private void OnLoaded(object sender, RoutedEventArgs e)
    {
        DummyListView.ItemsSource = VmList;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-08
    • 2012-08-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多