0

我无法终生弄清楚如何将行添加到 ListView。我不明白为什么当它适用于 ListBox(没有行)时它不起作用。我觉得我在这里错过了一些非常简单的东西,有人可以帮我吗?

编辑:抱歉没有粘贴所有代码

<ListView Margin="10" Name="lvUsers">
        <ListView.View>
                <GridView>
                        <GridViewColumn Header="Name" Width="120" />
                        <GridViewColumn Header="Age" Width="50" />
                        <GridViewColumn Header="Mail" Width="150" />
                </GridView>
        </ListView.View>


<StackPanel Orientation="Horizontal" Height="45"> <!--Stacks Items Horizontally-->
                            <ComboBox Width="100" Height="30">
                                <ComboBoxItem IsSelected="True">DirecTV</ComboBoxItem>
                                <ComboBoxItem>Hyundai</ComboBoxItem>
                                <ComboBoxItem>None</ComboBoxItem>
                            </ComboBox>
                            <TextBox Width="445" Height="30" Text="Follow RedZone on Twitter" VerticalContentAlignment="Center"/>
                            <CheckBox IsChecked="True" VerticalAlignment="Center">
                                <CheckBox.LayoutTransform>
                                    <ScaleTransform ScaleX="1.5" ScaleY="1.5"></ScaleTransform>
                                </CheckBox.LayoutTransform>
                            </CheckBox>
                        <Button Content="Delete"  Height="Auto" Width="Auto" HorizontalAlignment="Right" VerticalAlignment="Top" VerticalContentAlignment="Top"/>
                    </StackPanel>
</ListView>
4

1 回答 1

1

正如评论部分所建议的那样,将您的ListView(尽管您的代码看起来像您的目标是DataGrid)绑定到某个集合,它将为集合中的每个元素创建一个“行”。

您可以定义列并将它们绑定到元素的属性

    <DataGrid Margin="10" Name="lvUsers" ItemsSource="{Binding YourCollection}">
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding Name}"/>
            <DataGridTextColumn Binding="{Binding Age}"/>
            <DataGridTextColumn Binding="{Binding Mail}"/>
        </DataGrid.Columns>    
    </DataGrid>

此外,您需要将DataContext窗口设置为包含您的集合的类(称为 ViewModel)

<Window.DataContext>
   <local:MyViewModel/>
</Window.DataContext>

如果您不熟悉 MVVM 或 Bindings,这里有一些链接可以帮助您入门

MVVM:

http://msdn.microsoft.com/en-us/magazine/dd419663.aspx

http://www.codeproject.com/Articles/36545/WPF-MVVM-Model-View-View-Model-Simplified

http://www.codeproject.com/Articles/165368/WPF-MVVM-Quick-Start-Tutorial

绑定:

http://www.codeproject.com/Articles/140621/WPF-Tutorial-Concept-Binding

http://msdn.microsoft.com/en-us/library/ms752347.aspx

祝你好运

于 2013-09-25T18:36:37.740 回答