【问题标题】:Getting data from ListView从 ListView 获取数据
【发布时间】:2013-09-28 18:11:34
【问题描述】:

我在 XAML 中创建了一个ListView,但我不知道如何获取所选行的数据。谁能帮帮我?

这是我的 XAML:

<ListView x:Name="myListView" Margin="10,71,10,45" SelectionChanged="Selector_OnSelectionChanged">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Test1" DisplayMemberBinding="{Binding test1}" Width="400" />
            <GridViewColumn Header="Test2" DisplayMemberBinding="{Binding test2}" Width="120"/>
            <GridViewColumn Header="Test3" DisplayMemberBinding="{Binding test3}" Width="100"/>
        </GridView>
    </ListView.View>
</ListView>

【问题讨论】:

    标签: c# wpf xaml listview selecteditem


    【解决方案1】:

    你需要做以下

    1 设置数据结构:您可以在代码后面或 XAML 中进行。数据必须是一个集合类型,该集合具有 test1/test2/test3 数据成员。

    var data = new ObservableCollection<Test>();  
    data.Add(new Test {test1="abc", test2="abc2", test3="abc3"});  
    data.Add(new Test {test1="bc", test2="bc2", test3="bc3"});  
    data.Add(new Test {test1="c", test2="c2", test3="c3"}); 
    
    Data = data
    

    public ObservableCollection<Test> Data {get;set;}
    

    通过属性暴露数据

    2 您需要将集合(步骤 1 中的设置)分配给 ListView 的 DataContext。 (最好在 XAML 中,但可以在代码隐藏中完成)

    <ListView x:Name="myListView" DataContext={Binding Data} Margin="10,71,10,45" SelectionChanged="Selector_OnSelectionChanged" >
    

    3 还需要关联 View Model 类(包含Data)才能查看

    <Application
        x:Class="BuildAssistantUI.App"
        xmlns:local="clr-namespace:MainViewModel"
        StartupUri="MainWindow.xaml"
        >
    
        <Application.Resources>
            <local:MainViewModel x:Key="MainViewModel" />
        </Application.Resources>
    
    
     <Window DataContext="{StaticResource MainViewModel}" >
    

    完成上述步骤后,您应该会在ListView 中看到数据。


    关于如何从匿名类型的对象中访问属性,这是通过反射来完成的。

    以下是一个例子

    object item = new {test1="test1a", test2="test2a", test3="test3a"};
    var propertyInfo = item.GetType().GetProperty("test1"); // propertyInfo for test1
    var test1Value = propertyInfo.GetValue(item, null);
    

    【讨论】:

    • 谢谢,但我知道如何添加数据。我需要知道如何通过代码获取选定行的数据
    • 我想我误读了这个问题。你可以使用ListView.SelectedItems属性
    • 通过这段代码,我得到了所选行的完整数据:myListView.SelectedItems[0];如何获取一列的数据?
    • 你需要投射它。 ((Test)myListView.SelectedItems[0]).test1
    • 我必须使用什么类而不是 Test 来投射它?我以这种方式添加数据: myListView.Items.Add(new { test1 = "", test2="", test3 = ""});
    猜你喜欢
    • 2011-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-12
    • 2016-08-04
    • 1970-01-01
    相关资源
    最近更新 更多