How to get value of selected listbox item - c#

I'm loading data from an xml file into a listbox . Here is my xaml
<ListBox x:Name="lstSearchCategory" FontFamily="Arial Black"
VerticalAlignment="Center" Margin="25,69,19,10" Height="264">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel >
<Image Source="{Binding Image}" Height="100" Width="100"
HorizontalAlignment="Left"></Image>
<TextBlock HorizontalAlignment="Right" Text="{Binding Name}"
FontSize="30" Foreground="Black" Margin="140,-100,0,0"/>
<TextBlock Text="{Binding Category}" FontSize="24"
Foreground="Black" Margin="10,-10,0,0"/>
<TextBlock Text="{Binding Price}" HorizontalAlignment="Right"
Foreground="Red" Margin="300,-25,0,16"/>
<Rectangle Width="500" Fill="Black" Height="0.5"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
This is working fine. Now I want that when I select any listbox item, I get its respective values i.e image, price, category etc. How can i do this ? Help

You need to get the selected item in a ListBox Event and get the DataTemplate from the ListBox (as seen on MSDN):
private void lstEvents_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListBoxItem lbi = (lstEvents.ItemContainerGenerator.ContainerFromIndex(lstEvents.SelectedIndex)) as ListBoxItem;
ContentPresenter cp = GetFrameworkElementByName<ContentPresenter>(lbi);
DataTemplate dt = lstEvents.ItemTemplate;
Label l = (dt.FindName("lblEventId", cp)) as Label;
MessageBox.Show(l.Content.ToString());
}

You need generate Tap = "lstSearchCategory_Tap" in your XAML file and below code in .cs file
private void lstSearchCategory_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
try
{
ListBox ListBoxSelecteditem = (ListBox)sender;
YourModel model = (YourModel)ListBoxSelecteditem.SelectedItem;
string name = model.Name;
string cat = model.Category;
.......
string ControlName = ((System.Windows.FrameworkElement)
(((System.Windows.RoutedEventArgs)(e)).OriginalSource)).Name;
if (ControlName.ToLower() != "name".ToLower())
{
}
}
catch (Exception ex)
{ }
}

try this
<ListBox Tap="lstSearchCategory_Tap" x:Name="lstSearchCategory">
and than on tap event add this
var selected = (classname)lstSearchCategory.SelectedValue;
MessegeBox.Show(selected.Name + selected.Price);
here class-name is name of class where you are binding the name, price etc values

If you fill your ListBox via binding, you should have some property lile SelectedItem in your view model. So the currently selected item should always be stored in the viewmodel for easy access. Just add a binding to SelectedItem in your viewmodel and every thing should work.

Related

C# WIN UI 3: I have combobox with custom-typed observable collection as itemssource. Need help getting selected item

very new to C# WPF/WIN UI. My combobox displays my collection perfectly. But now when I want to do something with what the user selected I can't find the correct syntax in my 'SelectionChanged' event handler. I want to get the 'Market_ID' somehow. (FYI, I am not using MVVM yet as I don't understand how to implement, but I will learn. (really liking c#))
<ComboBox x:Name="cmbMarketID" PlaceholderText="Select Market ID" Width="500" Margin="5,5,0,0" RelativePanel.RightOf="border1" RelativePanel.Below="cmbState" ItemsSource="{x:Bind marketIdent}" SelectionChanged="cmbMarketID_SelectionChanged" SelectedItem="{Binding Market_ID}">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock x:Name="cmbo_market_ID" Text="{Binding Market_ID}" Width="15" TextAlignment="Right"/>
<TextBlock Text="{Binding Product}" Width="145" Margin="10,0,10,0" FontWeight="SemiBold"/>
<TextBlock Text="{Binding Company}" Width="70" Margin="10,0,10,0"/>
<TextBlock Text="{Binding System}" Margin="10,0,10,0"/>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
Here is the event handler: (I used a simple string first, and that worked, but now I need to use a typed-collection)
private void cmbMarketID_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (cmbMarketID.SelectedIndex == -1)
{
// Do not execute event
}
else
{
//string mktid = cmbMarketID.SelectedItem.ToString().Substring(0, 2).TrimEnd();
//string mktid = cmbMarketID.SelectedItem;
int mktid = (int)cmbMarketID.SelectedItem(); <-------what should the correct syntax be here?
//v_metric_mktid = mktid;
}
}
Cast the SelectedItem property to your type.
For example, if marketIdent is an IEnumerable<YourClass>:
var item = cmbMarketID.SelectedItem as YourClass;
Or if marketIdent is an IEnumerable<int>:
if (mbMarketID.SelectedItem != null)
{
var mktid = (int)mbMarketID.SelectedItem;
}

How to get string value from Listbox as user selected?

I can't get string value from Listbox after selected one item.
In my Listbox I have the Image (blinding source) and TextBlock (blinding source).
My code at .xaml page:
<ListBox Name="carListBox" Height="431" Canvas.Left="28" Canvas.Top="65" Width="446" SelectionChanged="ListBoxOnSelection">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image Name="brandImage" Source="{Binding Image}" Width="100" Height="150"></Image>
<Image Name="carImage" Source="{Binding Image}" Width="150" Height="150"></Image>
<TextBlock Name="textDisplay" Text="{Binding ShowDetail}" HorizontalAlignment="Center" VerticalAlignment="Center"></TextBlock>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
My code at .xaml.cs page (C#)
private void ListBoxOnSelection(object sender, SelectionChangedEventArgs args)
{
MessageBox.Show(carListBox.SelectedItem.ToString());
string saveData = carListBox.SelectedItem.ToString();
}
MessageBox can't show string value and I can't get value after user selected.
MessageBox show [1]https://i.imgur.com/2VSjhgN.jpg
You have to somehow get the Car object before you can have access to it's properties.
Something like this:
private void ListBoxOnSelection(object sender, SelectionChangedEventArgs args)
{
Car myCar=carListBox.SelectedItem as Car;
if(myCar != null)
MessageBox.Show(myCar.ShowDetail); //or any property.
}

SelectedIndex or SelectedItem of ListPicker with DataTemplate

I am using Listpicker to allow users to select color.
So i used a Toolkit Listpicker with a DataTemplate that includes Textbox to display its list items. What I want is when the page loads, the previously selected color(item) gets automatically selected. But it is giving me an obvious 'System.InvalidOperationException' exception because the items are not added simply but via datatemplate textbox. Please help me :
<toolkit:ListPicker x:Name="BackgroundColor" FullModeHeader="Select Background Color:" Header="Background Color:" BorderThickness="0" FullModeItemTemplate="{StaticResource PickerFullModeItemTemplate}" ItemTemplate="{StaticResource PickerItemTemplate}" Background="#FF09043C" SelectionChanged="BackgroundColor_SelectionChanged" >
</toolkit:ListPicker>
<phone:PhoneApplicationPage.Resources>
<DataTemplate x:Name="PickerItemTemplate">
<TextBlock Text="{Binding BackGroundColorString}" />
</DataTemplate>
<DataTemplate x:Name="PickerFullModeItemTemplate" >
<Grid x:Name="rootGrid" Margin="0">
<StackPanel Orientation="Horizontal">
<TextBlock Name="BackgroundColor"
Text="{Binding BackGroundColorString}"
/>
</StackPanel>
</Grid>
</DataTemplate>
</phone:PhoneApplicationPage.Resources>
if (SunderGutkaSettings.Contains(SG_KEY_BACKGROUNDCOLOR)) //check if key is not present, read value
{
if (BackGroundColorList.Count != 0)//test if list if not empty
{
var ListPickerBackGroundColorRead = BackGroundColorList[singletonInstance.SelectedFontColorIndex] as BackGroundlistPickerClass; //pull whole class
string ListPickerBackGroundColorReadString = ListPickerBackGroundColorRead.BackGroundColorString;
int ListPickerBackGroundColorReadStringToIndex = BackGroundColorList.FindIndex(x => x.BackGroundColorString.StartsWith(ListPickerBackGroundColorReadString));
BackgroundColor.SelectedIndex = ListPickerBackGroundColorReadStringToIndex; //DISABLE FOR testing
}
Actually, on simplyfing my code :
BackgroundColor.SelectedIndex = 0; Doesnt work
nor does
BackgroundColor.SelectedItem="Red";
Help me
To Set the Item,
This.BackgroundColor.SelectedItem = YourObject;
This is how you get selecteditem of ListPicker, probably you need to cast to the object you bind to the list Picker
private void BackgroundColor_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var item = (sender as ListPicker).SelectedItem;
}

Navigate from Panorama Page to a non-Panorama Page (listitems)

Here is my xaml of the Panorama page item.
<controls:PanoramaItem x:Name="deeln" Header="Deelnemers" Style="{StaticResource subtitle}">
<!--Double line list with image placeholder and text wrapping-->
<ListBox Margin="12,0,-12,0" ItemsSource="{Binding ItemsDeelnemer}" x:Name="lbDeelnemer" SelectionChanged="lbDeelnemer_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<ScrollViewer HorizontalScrollBarVisibility="Visible" VerticalScrollBarVisibility="Disabled">
<StackPanel Orientation="Horizontal" Margin="0,0,0,17">
<TextBlock Foreground="Black" TextWrapping="Wrap" Text="{Binding LineNr}" Style="{StaticResource PhoneTextExtraLargeStyle}" ></TextBlock>
<StackPanel Width="430" Height="100">
<TextBlock Foreground="Black" TextWrapping="Wrap" Text="{Binding LineNaamWielrenner1}" Style="{StaticResource PhoneTextExtraLargeStyle}" FontSize="35"></TextBlock>
<TextBlock Foreground="Black" TextWrapping="Wrap" Text="{Binding LineNaamWielrenner2}" Style="{StaticResource PhoneTextExtraLargeStyle}" FontSize="35"></TextBlock>
</StackPanel>
</StackPanel>
</ScrollViewer>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</controls:PanoramaItem>
Here is my code in the Panorama page.
private void lbDeelnemer_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
#region go to specific deelnemerinfo screen
// If selected index is -1 (no selection) do nothing
if (lbDeelnemer.SelectedIndex == -1)
return;
// Navigate to the new page
if (lbDeelnemer.SelectedIndex == 0)
{
NavigationService.Navigate(new Uri("/DeelnemerInfo.xaml", UriKind.Relative));
//NavigationService.Navigate(new Uri("/DeelnemerInfo.xaml?selectedItem=" + lbDeelnemer.SelectedIndex, UriKind.Relative));
}
// Reset selected index to -1 (no selection)
lbDeelnemer.SelectedIndex = -1;
#endregion
}
Here is my code from the non panorama page.
protected override void OnNavigatedTo(NavigationEventArgs e)
{
//second try
string strItemIndex;
if (NavigationContext.QueryString.TryGetValue("goto", out strItemIndex))
PanoramaControl.DefaultItem = MyPanorama.Items[Convert.ToInt32(strItemIndex)];
base.OnNavigatedTo(e);
//first try
string selectedIndex = "";
if (NavigationContext.QueryString.TryGetValue("selectedItem", out selectedIndex))
{
int index = int.Parse(selectedIndex);
DataContext = App.ViewModel.ItemsDeelnemer[index];
}
}
My problem, I want to navigate like you do with a default databound application. You click on the first listitem and you go to a new page (non panorama).
It looks simple but i can't find it.
Try binding the tag attribute to the index/itemvalue
<ListBox>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<HyperlinkButton Tag="{Binding FileName}" Click="location_Click"/>
<TextBlock Text="{Binding DateCreated}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
navigate accordingly
private void location_Click(object sender, RoutedEventArgs e)
{
HyperlinkButton clicked = (HyperlinkButton)sender;
string uri = "/noteapp;component/ViewEdit.xaml?id=" + clicked.Tag;
NavigationService.Navigate(new Uri(uri, UriKind.Relative));
}
and on panaroma page use this something like this to retrieve the value
filename = NavigationContext.QueryString["id"];
var storage = IsolatedStorageFile.GetUserStoreForApplication();
using (var file = storage.OpenFile(filename, FileMode.Open))

accessing an item variable from dynamic data in listbox on SelectionChanged

I am populating a listbox from a webcclient, the data is binded to the listbox and not saved anywhere..
Id like to access binded information when the user selects from the listbox
im having trouble accessing the value of a text block from the SelectionChanged event..
<ListBox x:Name="UsersListBox" ItemsSource="{Binding Items}" Height="471" VerticalAlignment="Top" HorizontalAlignment="Left" Width="457" SelectionChanged="TargetsListBox_SelectionChanged" Grid.ColumnSpan="2">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Margin="0,0,0,17" Width="432" Orientation="Horizontal">
<Image x:Name="ImageAddIcon" Source="blkAdd.png" Height="60" Width="71" VerticalAlignment="Stretch" />
<Image x:Name="ImagePointer" Source="blkClick.png" Height="60" Width="71" VerticalAlignment="Stretch" />
<StackPanel>
<TextBlock Name="txtID" Text="{Binding PlayerID}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}" Foreground="#FF8A9A8A" Visibility="Collapsed" />
<TextBlock Name="txtNick" Text="{Binding Nickname}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}" Foreground="#FF8A9A8A" />
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Id like to access the PlayerID from this dynamicly populated list(from webservice) on a onselected basis
private void TargetsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
string ID = UsersListBox.SelectedItem ???PlayerID or txtID???;
}
i just want to get the player id that is binded to the listbox with a selection changed event ANY IDEAS!!!!!!!!! <3
Assuming that "Items" is a ObservableCollection:
private void TargetsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var listBox = sender as ListBox;
var selectedItem = listBox.SelectedItem as Player;
if (selectedItem != null)
{
string id = selectedItem.PlayerID
string nick = selectedItem.NickName;
}
}

Categories