Get data from selected row in Gridview in C #, WPF

I am trying to get data from a Gridview that I created in XAML.

<ListView Name="chartListView" selectionChanged="chartListView_SelectionChanged">
  <ListView.View>
     <GridView>
        <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}" Width="250"/>
        <GridViewColumn Header="Type" DisplayMemberBinding="{Binding Type}" Width="60"/>
        <GridViewColumn Header="ID" DisplayMemberBinding="{Binding ID}" Width="100"/>
     </GridView>
  </ListView.View>
</ListView>

I saw this code: -

GridViewRow row = GridView1.SelectedRow;
TextBox2.Text = row.Cells[2].Text;

However, my problem is that my GridView is created in XAML and is not called, i.e. I can’t (or don’t know how) create a link to "gridview1" and therefore cannot access the objects inside it.

Can I name or link to my gridview from either C # or XAML to use the code above?

Secondly, can I then access the elements of the array by name instead of index, for example: -

TextBox2.Text = row.Cells["ID"].Text

Thanks for any help.

+3
source share
2 answers

Yes you can name your gridview:

<GridView x:Name="chartGridView">
    ...
</GridView>

, :

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

#.

+1

- . , - . , XAML:

<TextBox x:Name="TextBox2" Text={Binding SelectedItem.ID, ElementName=chartListView}"/>

WPF , . - . , :

string UglyHack(string name)
{
    var columns = (chartListView.View as GridView).Columns;
    int index = -1;
    for (int i = 0; i < columns.Count; ++i)
    {
        if ((columns[i].Header as TextBlock).Text == name)
        {
            index = i;
            break;
        }
    }
    DependencyObject j = SelectedListView.ItemContainerGenerator.ContainerFromIndex(SelectedListView.SelectedIndex);
    while (!(j is GridViewRowPresenter)) j = VisualTreeHelper.GetChild(j, 0);
    return (VisualTreeHelper.GetChild(j, index) as TextBlock).Text;
}
+1

Source: https://habr.com/ru/post/1720426/


All Articles