Reputation: 41
I am trying to retrieve data from a Gridview that I have 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 have seen some code like this :-
GridViewRow row = GridView1.SelectedRow;
TextBox2.Text = row.Cells[2].Text;
However my problem is that my GridView is created in XAML, and is not named, ie I cannot (or do not know how to) create a reference to 'gridview1', and therefore cannot access objects within it.
Can I name or create a reference to my gridview either from c# or XAML so I can use the above code?
Secondly, can I then access the array elements by name instead of index, something like :-
TextBox2.Text = row.Cells["ID"].Text
Thanks for any help.
Upvotes: 3
Views: 14884
Reputation: 4820
You're doing something horribly wrong. You should not be trying to read data from grid cells, but from your business objects directly. And you should avoid procedural code when a pure XAML solution exists:
<TextBox x:Name="TextBox2" Text={Binding SelectedItem.ID, ElementName=chartListView}"/>
WPF is not intended to be used like you're trying to. So reading individual grid cells is a dirty hack. That said, it goes something like this:
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;
}
Upvotes: 3
Reputation: 137198
Yes you can name your gridview:
<GridView x:Name="chartGridView">
...
</GridView>
Make sure the following is included in the Window definition:
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
This will enable you to reference it from your c# code.
Upvotes: 1