如何从ListView
选定的单元格中获取文本?
我有一个单击即可ListView
创建列表。Button
我想通过右键单击检索 Car 列的文本值。我不知道正确的命令是什么。SelectedItem.ToString()
没有提供预期的结果。
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();
}