How can I get the text from a ListView
selected cell?
I have a ListView
that creates a list with a Button
click. I'd like to retrieve the text value of the Car column with a right click. I don't know what the correct command for this is. SelectedItem.ToString()
is not providing the desired results.
XAML:
<Grid>
<ListView x:Name="carList" VerticalAlignment="Top">
<ListView.ContextMenu>
<ContextMenu>
<MenuItem Header="Get Value" Click="GetValue_Click"/>
</ContextMenu>
</ListView.ContextMenu>
<ListView.View>
<GridView>
<GridViewColumn Header="Car" DisplayMemberBinding="{Binding Name}" Width="Auto"/>
<GridViewColumn DisplayMemberBinding="{Binding Make}" Header="Make" Width="Auto"/>
<GridViewColumn DisplayMemberBinding="{Binding Year}" Header="Year" Width="Auto"/>
</GridView>
</ListView.View>
</ListView>
<Button x:Name="generate" Content="Create List" Click="generate_Click" Margin="0,0,5,5" DockPanel.Dock="Top" VerticalAlignment="Bottom" HorizontalAlignment="Right" Width="88"/>
<TextBox x:Name="textbox" HorizontalAlignment="Left" Height="23" Margin="5,0,0,5" TextWrapping="Wrap" VerticalAlignment="Bottom" Width="386"/>
</Grid>
CS:
public MainWindow()
{
InitializeComponent();
}
public class Car
{
public string Name { get; set; }
public string Make { get; set; }
public string Year { get; set; }
}
private void generate_Click(object sender, RoutedEventArgs e)
{
List<Car> cars = new List<Car>();
int i = 0;
string[] name = { "Sentra", "IS", "Camry" };
string[] make = { "Nissan", "Lexus", "Toyota" };
string[] year = { "2000", "2011", "2013" };
foreach (string s in name)
{
cars.Add(new Car() { Name = name[i], Make = make[i], Year = year[i] });
i++;
}
carList.ItemsSource = cars;
}
private void GetValue_Click(object sender, RoutedEventArgs e)
{
//Get text value from Car class, Name property
//What is the correct code to access this?
textbox.Text = carList.SelectedItem.ToString();
}