简体   繁体   English

c# wpf 访问列表视图列中的值

[英]c# wpf access value in column of listview

I have a ListView bound to XML.我有一个绑定到 XML 的 ListView。 The XAML looks like this: XAML 看起来像这样:

<ListView Name="patientsListView" ItemsSource="{Binding}" SelectionChanged="patientsListView_SelectionChanged">
    <ListView.View>
        <GridView x:Name="patientGrid">
            <GridViewColumn Header="PatientName" Width="Auto" DisplayMemberBinding="{Binding XPath=PatientName}" />
            <GridViewColumn Header="PatientAccountNumber" Width="Auto" DisplayMemberBinding="{Binding XPath=PatientAccountNumber}" />
            <GridViewColumn Header="DateOfBirth" Width="Auto" DisplayMemberBinding="{Binding XPath=DateOfBirth}" />
        </GridView>
    </ListView.View>
</ListView>

When a row is clicked, I want to do something:单击一行时,我想做一些事情:

private void patientsListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
        //do stuff
        MessageBox.Show();
        }

If I click on a row, how do I access a value in a column individually?如果单击一行,如何单独访问列中的值? When debugging, I can see in Locals in the listview SelectedItems that my data is in the the InnerText in the Results View for whatever index, but I don't know how to get the value in code.调试时,我可以在列表视图 SelectedItems 的 Locals 中看到我的数据位于结果视图中的 InnerText 中,无论索引如何,但我不知道如何获取代码中的值。

var patient = ((ListViewItem) sender).Content as Patient; //or whatever object type

From there you can get patient.PatientName , etc从那里你可以得到patient.PatientName

[EDIT] Now that I look at it, I'm not 100% sure this will work within a selectionchanged event. [编辑] 现在我看了它,我不是 100% 确定这会在 selectionchanged 事件中起作用。 But it will work on a row click event.但它适用于行点击事件。

However, if you're just trying to update another part of the UI, you can do something like this:但是,如果您只是想更新 UI 的另一部分,则可以执行以下操作:

<TextBlock Text="{Binding SelectedItem.PatientName,ElementName='patientGrid'}"/>

In Debug mode find out the type of listview.SelectedItems, than convert it in that type在调试模式下找出 listview.SelectedItems 的类型,然后将其转换为该类型

var item = (ItemType)listview.SelectedItems

than you can get value you want like this比你能得到你想要的价值

item.PatientName

您可以将senderobject更改为dynamic并继续对其他列使用dynamic

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM