将 设置为ListBox.SelectedValuePath
Binded 类中表示您需要的值的成员的名称。这样你应该能够通过ListBox.SelectedValue
编辑(示例):
<ListBox x:Name="TestListBox" ItemsSource="{Binding}" SelectedValuePath="LastName" MouseDoubleClick="TestListBox_MouseDoubleClick">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=FirstName}" Width="110" />
<TextBlock Text="{Binding Path=Age}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
代码隐藏:
public partial class MainWindow: Window
{
public MainWindow( )
{
InitializeComponent( );
var persons = new System.Collections.ObjectModel.ObservableCollection<Person>();
persons.Add( new Person( ) { FirstName = "Walter" , LastName = "Bishop" , Age = 63 } );
persons.Add( new Person( ) { FirstName = "Peter" , LastName = "Bishop" , Age = 33 } );
persons.Add( new Person( ) { FirstName = "Olivia" , LastName = "Dunham" , Age = 33 } );
TestListBox.DataContext = persons;
}
private void TestListBox_MouseDoubleClick( object sender , MouseButtonEventArgs e )
{
if ( TestListBox.SelectedItem != null )
{
MessageBox.Show( (string)TestListBox.SelectedValue );
}
}
}
public class Person
{
public string FirstName { get; set; }
public string LastName{get;set;}
public int Age { get; set; }
}