2

我想以编程方式填充 WPF 列表视图。我认为我接近答案但尚未解决,我使用一种方法来填充列表视图,列表视图在 XAML 中看起来像这样

<ListView Name="listview" HorizontalAlignment="Left" Height="252" Margin="39,110,0,0" VerticalAlignment="Top" Width="340">
        <ListView.View>
            <GridView x:Name="gridcontrol">
                <GridViewColumn/>
            </GridView>
        </ListView.View>
</ListView>

到目前为止我所做的是:

private void FillListView( String[] texto ) {

        GridViewColumn gvc = new GridViewColumn();
        gvc.Header = cmbx2.SelectedItem.ToString();
        gridcontrol.Columns.Add(gvc);

        foreach (String s in texto) {

            ListViewItem item = new ListViewItem();
            item.Content = s;
            listview.Items.Add(item);

        }

        listview.View = gridcontrol;
    }
4

1 回答 1

0

一个更简单的解决方案而不是搞乱 ListViewItems 是填充一个集合并将数据绑定到它。诀窍是翻转侧面的项目控件,以便您的字符串集合显示为列而不是行。

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">

    <ItemsControl ItemsSource="{Binding Path=Results}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <TextBlock Text="{Binding Path=Item1}" FontWeight="Bold" />
                    <ItemsControl ItemsSource="{Binding Path=Item2}" />
                </StackPanel>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <StackPanel Orientation="Horizontal" />
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
    </ItemsControl>

</Window>

后面的代码:

using System;
using System.Collections.ObjectModel;
using System.Windows;

namespace WpfApplication1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            Results = new ObservableCollection<Tuple<string, string[]>>();

            FillListView("AAA", new string[] { "A1", "A2", "A3" });
            FillListView("BBB", new string[] { "B1", "B2", "B3" });

            DataContext = this;
        }

        public ObservableCollection<Tuple<string, string[]>> Results { get; private set; }

        private void FillListView(string header, string[] text)
        {
            Results.Add(Tuple.Create(header, text));
        }
    }
}
于 2012-11-27T16:10:36.607 回答