views:

60

answers:

3

I have a listbox in a Silverlight C# app which is binded to some data from a database in XAML:

<StackPanel>
      <TextBlock x:Name="ItemText" Text="{Binding Name}" Foreground="White" FontSize="35" TextAlignment="Left"/>
      <TextBlock x:Name="DetailsText" Text="{Binding Description}" Foreground="Gray" Margin="0,-6,0,3" />
</StackPanel>

Now in code behind file, i am trying to get the string "Name" (binded above) based on the selection user makes in the listbox.

I tried the SelectedIndex property of listbox but it only returns integer. Can anyone help me?

A: 

Try to use the SelectedItem property instead

Edit: Or even better bind the SelectedItem property to a value in your ViewModel if you use the MVVM pattern in your application.

Rune Grimstad
A: 

I think , ListBox's ItemSource poperty is binded to some custom collection of objects

1- if you handeling selectionchanged event than you can use SelectedItem property

that means

CustomObject obj = lstName.SelectedItem as CustomObject


if(obj!=null)

{
   string name = obj.Name;
}

where lstName is name of your listbox

and CustomObject is the type of object in the ItemSource property of listbox

saurabh
ok i tried this but the object is returning null.EDIT: void client_GetNewsPublishersCompleted(object sender, NewsService.GetNewsPublishersCompletedEventArgs e) { lbStoreMenu.ItemsSource = e.Result; }
Taimi
private void lbStoreMenu_SelectionChanged(object sender, SelectionChangedEventArgs e) { System.Collections.ObjectModel.ObservableCollection<NewsService.News_Publisher> obj = lbStoreMenu.SelectedItem as System.Collections.ObjectModel.ObservableCollection<NewsService.News_Publisher>; if(obj!=null) { app.IdNewsStoreSelectedItem = obj.First().Name; } NavigationService.Navigate(new Uri("/NewsStoreDetailsPage.xaml", UriKind.Relative)); }
Taimi
try this lbStoreMenu.SelectedItem as NewsService.News_Publisher
saurabh
ok ignore my last comment. I have got it to work using the method you wrote. Thanks alot !
Taimi
A: 

Have you tried using , SelectedItem property and if it is not null then try to find the TextBlock with Name as the Child of the SelectedItem using VisualTreeHelper ?

Siva Gopal