问题
I have a ListBox in a WPF Page each Item of which consists of two Labels. I have assigned them the names FirstName, LastName:
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Name="FirstName" Text="{Binding FirstName}" Margin="0,0,10,0"/>
<TextBlock Grid.Column="1" Name="LastName" Text="{Binding LastName}" HorizontalAlignment="Left"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
When the user selects an Item of the Listbox, I want to hold their values separately in order to pass them to another Page. I try to this end in the code behind the code:
ListItemCollection lbi = List1.SelectedItem as ListItemCollection;
string first = lbi.FirstListItem.DataContext.ToString();
string last = lbi.LastListItem.DataContext.ToString();
However I get a nullReferenceException at the definition of strings? What is wrong in this way? How can I get the SelectedItem values?
Update: The Binding values derive from an SQLAdapter with a SQL Query. See the code behind:
SqlDataAdapter dAdapt1 = new SqlDataAdapter(sqlStr1, cnStr);
DataSet dataSet1 = new DataSet();
dAdapt1.Fill(dataSet1);
List1.DataContext = dataSet1.Tables[0];
回答1:
DataTable and ListBox##
myDataSet.BookTable. firstColumn and lastColumn.
binding ready
1.
adapter.Fill(myDataSet, "BookTable");
2.
myListBox.DataContext = myDataSet;
binding begin
3.XAML
<ListBox ItemsSource="{Binding Path=BookTable}"
4. Window.Resources>
<DataTemplate x:Key="BookItemTemplate">
<Grid>
<TextBlock Text="{Binding Path=first}" Grid.Column="0"/>
<TextBlock Text="{Binding Path=last}" Grid.Column="1" />
5.
ItemTemplate ="{StaticResource BookItemTemplate}"/>
binding end
6.
DataRowView d1=List1.SelectedItem as DataRowView;
string first =d1["first"].tostring();
string last =d1["last"].tostring();
回答2:
As Andy has already commented, List1.SelectedItem
is not a ListItemCollection
, so you cannot cast to that type, hence lbi
is null
.
In the DataTemplate you're binding to properties FirstName
and LastName
. There must be a class that defines these properties, let's call it Person
.
I guess the following, because you haven't shown it. You're binding the ItemSource
of the ListBox to a collection of Person
objects, provided by some property of the object that is returned by dataSet1.Tables[0]
(because you set List1.DataContext
to that value).
So what you would have to write to get the selected item is this:
Person lbi = List1.SelectedItems as Person;
and replace Person
by whatever that type really is in your application.
来源:https://stackoverflow.com/questions/9239003/get-the-values-of-a-selecteditem-in-wpf