If we are using the DataGrid to get the value from the column I can use
var a = datagrid1.Columns[1].GetCellContent(item)
Can anyone please tell me how can I get the same value when using ListView instead of DataGrid. This ListView contains a GridView.
Try this
xaml
<ListView Margin="10" Name="UsersList" SelectionChanged="UsersList_SelectionChanged_1">
<ListView.View>
<GridView>
<GridViewColumn Header="Name" Width="120">
<GridViewColumn.CellTemplate>
<DataTemplate>
<Grid x:Name="colGrid">
<TextBlock Text="{Binding Name}" x:Name="txtBlock"/>
</Grid>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="Age" Width="50">
<GridViewColumn.CellTemplate>
<DataTemplate>
<Grid x:Name="colGrid">
<TextBlock Text="{Binding Age}" x:Name="txtBlock"/>
</Grid>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="Mail" Width="150">
<GridViewColumn.CellTemplate>
<DataTemplate>
<Grid x:Name="colGrid">
<TextBlock Text="{Binding Mail}" x:Name="txtBlock"/>
</Grid>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
SelectionChanged Event Handler of List View
private void UsersList_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
{
var gridView = UsersList.View as GridView;
ListBoxItem myListBoxItem =UsersList.ItemContainerGenerator.ContainerFromItem(UsersList.SelectedItem) as ListBoxItem;
//ContentControl does not directly host the elements provided by the expanded DataTemplate.
//It uses a ContentPresenter to do the work.
//If we want to use the FindName method we will have to pass that ContentPresenter as the second argument, instead of the ContentControl.
ContentPresenter myContentPresenter = myListBoxItem.GetVisualChild<ContentPresenter>();
foreach (var column in gridView.Columns)
{
//Here using FindName we can get the controls of cell template
var grid = column.CellTemplate.FindName("colGrid", myContentPresenter);
}
}
Visual Helper
public static class VisualHelper
{
public static T GetVisualChild<T>(this Visual parent) where T : Visual
{
T child = default(T);
for (int index = 0; index < VisualTreeHelper.GetChildrenCount(parent); index++)
{
Visual visualChild = (Visual)VisualTreeHelper.GetChild(parent, index);
child = visualChild as T;
if (child == null)
child = GetVisualChild<T>(visualChild);//Find Recursively
else
return child;
}
return child;
}
}
I hope this will help.