简体   繁体   中英

c# wpf access value in column of listview

I have a ListView bound to XML. The XAML looks like this:

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

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

From there you can get patient.PatientName , etc

[EDIT] Now that I look at it, I'm not 100% sure this will work within a selectionchanged event. 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:

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

In Debug mode find out the type of listview.SelectedItems, than convert it in that type

var item = (ItemType)listview.SelectedItems

than you can get value you want like this

item.PatientName

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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