访问列表视图的元素

时间:2016-12-12 17:05:54

标签: c# wpf xaml

我已按照此示例创建过滤后的列表视图: list view with gridview。 现在我想访问我的表的一个元素。实际上我的表被声明如下:

<ListView ScrollViewer.CanContentScroll="True" ScrollViewer.VerticalScrollBarVisibility="Visible" 
              Grid.Row="2" Name="Children" Grid.ColumnSpan="3">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="ID"  DisplayMemberBinding="{Binding ID}"/>
            </GridView>
        </ListView.View>

C#

List<Child> items = new List<Child>(); 

... 

foreach (string ID in IDS) items.Add(new Child() {ID=ID}); 

Children.ItemsSource = items

如何访问所选项目并获取ID字段?我知道这似乎是一个微不足道的问题,但经过几个小时的尝试后我有点沮丧。

3 个答案:

答案 0 :(得分:1)

你可以试试这个,

<强>的Xaml

<ListView ScrollViewer.CanContentScroll="True" ScrollViewer.VerticalScrollBarVisibility="Visible" PreviewMouseLeftButtonUp="listView_Click" Grid.Row="2" Name="Children" Grid.ColumnSpan="3">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="ID"  DisplayMemberBinding="{Binding ID}"/>
            </GridView>
        </ListView.View>
</ListView>

Code behind.cs

private void listView_Click(object sender, MouseButtonEventArgs e)
{
    var item = sender as ListViewItem;
    if (item != null && item.IsSelected)
    {

    }
}

答案 1 :(得分:0)

  

如何访问所选项目并获取ID字段?

您可以将ListView的SelectedItem属性强制转换为定义ID属性的类型(User或任何调用类的类型),例如:

User selectedUser = Children.SelectedItem as User;
if(selectedUser != null)
{
 var id = selectedUser.ID;
}

答案 2 :(得分:0)

关注您的代码:

<ListView ScrollViewer.CanContentScroll="True" 
         IsSynchronizedWithCurrentItem="True"
         SelectedItem="{Binding SelectedId, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
         ScrollViewer.VerticalScrollBarVisibility="Visible" 
         Grid.Row="2" Name="Children" Grid.ColumnSpan="3">
        <ListView.View>
            <GridView>
                <GridViewColumn 
                    Header="ID"  
                    DisplayMemberBinding="{Binding   ID}"/>
            </GridView>
        </ListView.View>
</ListView>

在您的ViewModel中,您应该拥有一个属性SelectedId,其ID列的类型相同。

当用户在ListView中选择ID时,所选的ID将位于您的属性SelectedId中。