Setting Label object as per Listbox selected item - c#

I need to bind a Label to two ListBoxes. In order to do this I have set the SelectionChanged property of both ListBoxes to the same function:
<ListBox Name="ListBox1" SelectionChanged="UpdateSelectedItem" />
<ListBox Name="ListBox2" SelectionChanged="UpdateSelectedItem" />
<Label Name="DetailsLabel" DataContent="DefinedElsewhere" />
However I am having trouble finding what the selected item actually is. I have gone through all the properties of the sending object and the SelectionChangedEventArgs but I cannot find it. The ListBox is bound to an ObservableCollection of objects, and I would like the Label to display the properties of the last selected item, no matter from which ListBox it was selected. How do I find that?
private void UpdateSelectedItem(object sender, SelectionChangedEventArgs e)
{
DetailsLabel.Content = ???;
}

You can read the selected item text doing something like:
ListBoxItem item = ((ListBox)sender).SelectedItem as ListBoxItem;
String itemText = (item != null) ? item.Content.ToString() : String.Empty;
You have to cast the SelectedItem property to the type of object you have in the list.
In this example I've used ListBoxItem.

Related

How can I get LongListSelector SelectedItem as a string in WP8

I have a longlistselector like the below image. now I wanna get the text of the item user's tapped. I've searched a lot but no solution found ;(
pay attention to the image please to give a sample code
http://amiryari.persiangig.com/image/stackoverflow-question.jpg
1) Wire up the SelectionChanged event on the LongListSelector control:
<phone:LongListSelector ItemsSource="{Binding MyListItems}"
SelectionChanged="LongListSelector_SelectionChanged">
2) Retrieve the selected item from the AddedItems collection in the SelectionChangedEventArgs:
private void LongListSelector_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (e.AddedItems.Count > 0)
{
var item = e.AddedItems[0];
}
}
3) If your item is an object, and the text is displayed through a property, then you would have access to the text through the property on your object:
MyListItemObject item = e.AddedItems[0] as MyListItemObject;
MessageBox.Show(item.FullName);
If your list is bound to a list of strings, then it would simply be the first item in the AddedItems collection:
string fullName = e.AddedItems[0].ToString();
MessageBox.Show(fullName);
You can always listen for the SelectionChanged event and obtain the string. There is another way if you are using a DataTemplate to style your items in the list. Declare Tapped event in DataTemplate like this:
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image Source="{Binding ContactImage}"/>
<TextBlock x:Name="NameTextBlock" Text="{Binding ContactName}" Tapped="NameTextBlock_Tapped"/>
</StackPanel>
</DataTemplate/>
Now in our code:
private void LongListSelector_SelectionChanged(object sender, BlahBlah e)
{
var tb = sender as Textblock;
string cName = tb.Text; //This is the string you wanted.
MessageBox.Show(cName);
}

Grid View Items contents in xaml (windows store app)

how can I get to the contents of the clicked grid Item in a grid view ... for example the grid item has a textbox ... how could I get the contents of this textbox when the gridview Item is clicked vie ItemClickEventArgs ?
thanks
Try this code.
<GridView x:Name="gv" SelectionChanged="gvSelectionChanged">
<GridViewItem>
<TextBox x:Name="txtOne" />
</GridViewItem>
<GridViewItem>
<TextBox x:Name="txtTwo" />
</GridViewItem>
</GridView>
private void gvSelectionChanged(object sender, SelectionChangedEventArgs e)
{
var SelectedText = ((TextBox)((GridViewItem)gv.SelectedItem).Content).Text;
}
Assuming you're using ItemsSource with your GridView, you can use e.ClickedItem to get the DataContext of the GridViewItem you clicked. If you want the actual GridViewItem you can use
GridViewItem item = (sender as GridView).ItemContainerGenerator.ContainerFromItem(e.ClickedItem) as GridViewItem;
Then you can use VisualTreeHelper.GetChild to dig down as necessary (like to find a TextBox).
If you are using a DataTemplate to display the items in the GridView, I have found the simplest way is to capture Tapped, Hold, etc.. event on the DataTemplate's control that holds all the item.
In the event you can code
private void ItemTapped(object sender, TappedRoutedEventArgs e)
{
var clickedItem = (sender as FrameworkElement).DataContext;
}
That will give you the object within the item that was clicked.

How to Assign ListBox Selected Items to Source Propertey

I want when a user selects one or multiple items that my source property gets updated. I have tried with the binding mode OneWayToSource but this is not helping. Below is the XAML and ViewModel code:
<ListBox x:Name="ItemsListBox" SelectionMode="Multiple" Height="300"
ItemsSource="{Binding ResultSet}"
SelectedItem="{Binding SelectedItems,Mode=OneWayToSource}">
private List<string> _selectedItems;
public List<string> SelectedItems
{
get
{
return _selectedItems;
}
set
{
_selectedModeItems = value;
NotifyPropertyChanged("SelectedItems");
}
}
I have taken the approach by using Attached behaviours and it works , but is there any simpler way?
Your question should be like this.
How to get multiple selected items from the ListBox in WPF with MVVM?
Well, you have the answer from following stackoverflow threads.
link 1
link 2
Simply you can define IsSelected property in your ResultSet view model. Then if you want to get selected items at any point, just get the items which the "IsSelected" property is set to true from the ResultSet.
you could also create an Attached Behavior
here is an Example how to do it
WPF ListBox has two properties related to the currently selected item:
SelectedItem available for binding, bound to the first selected item.
SelectedItems (with an 's' at the end) is not available to binding.
When multi selection is enabled, you want to have access to SelectedItems but unfortunately you can't bind to it
You can workaround this limitation using code behind.
Create a property named SelectedItems that will contain the selection, then subscribe the SelectionChanged event:
<ListBox x:Name="ItemsListBox" SelectionMode="Multiple" Height="300"
ItemsSource="{Binding ResultSet}"
SelectionChanged="ListBox_SelectionChanged">
private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
foreach (string item in e.RemovedItems)
{
SelectedItems.Remove(item);
}
foreach (string item in e.AddedItems)
{
SelectedItems.Add(item);
}
}

Getting item from Observable Collection or List()

I have a ListBox called NotesList. I have an ObservableCollection called noteList, and I have a TextBox called NoteContents.
In my ObservableCollection, I set the Filename and Contents properties for a few items and then it gets added (bound) to my ListBox.
But now, I want to (when I click a button), show the "Contents" of the ListBox Item that was selected in the NoteContents TextBox.
How can I do this?
I currently have:
private void NotesList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
NoteContents.Text = noteList.Where(x => x.Filename.Contains(NotesList.SelectedValue.ToString())).FirstOrDefault().Contents;
}
You can do this without button clicks, just binding like:
<ListBox Name="NotesList" ItemsSource="{Binding YourObservableCollection}">
<!--Your bindings here-->
</ListBox>
<TextBox Text="{Binding ElementName=NotesList, Path=SelectedItem.Contents}" />

Getting selected item string from bound ListBox

I'm having a problem with getting a string from a bound textblock within a listbox, when I use the code below, I can bind the listbox and the listbox has items showing up, but when the item in the list is clicked I don't get the proper string, I print a message box a message with objects names like
"MyApp.Item"
shows up instead. myApp is the name of the app and Item is the name of my model that I am binding to the listbox. The proper text from the selected item showed up when the listbox was not binded.
private void listBoxtrend_Tap(object sender, GestureEventArgs e)
{
selectedText = "";
selectedText = listBox.SelectedValue.ToString();
MessageBox.Show(selectedText);
}
xml
<ListBox ItemsSource="{Binding Item}" Foreground="RoyalBlue"
Height="395" HorizontalAlignment="Center"
Margin="12,111,0,0" Name="listBox"
VerticalAlignment="Top" Width="438"
TabIndex="10" Tap="listBox_Tap" >
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock TextWrapping="Wrap" FontSize="26" HorizontalAlignment="Left"
Name="tblItem" Text="{Binding ItemString}"
VerticalAlignment="Top" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
I'd really appreciate if you could help me thanks
You're binding to the ItemString in the DataTemplate's TextBlock and the Item Collection in the ListView. As such the SelectedValue will be of the Item type. You should actually be doing something like this in your Tap handler to get at the ItemString's value...
private void listBoxtrend_Tap(object sender, GestureEventArgs e)
{
selectedText = "";
var selected = listBox.SelectedValue as Item;
selectedText = selected.ItemString;
MessageBox.Show(selectedText);
}
In your example, the ToString is printing the name of the class. You could also override ToString in your Item model to be whatever you want the string to be.
Note: the types and such may be a bit off, I guessed a bit based off of what you wrote in your question. Also, there is no need to set selectedText to an empty string that will just be overwritten in the third line above. I wanted to keep it so you could get some idea of what I changed in your code.
It's very simple, try following:
string selectedText = ListBox.GetItemText(ListBox.SelectedItem);
You need to also set the SelectedItem of the Listbox to something.
SelectedItem = {Binding SelectedItem}
and rename your ItemsSource to "Items" as that makes more sense.
Your SelectedItem in your codebehind or your ViewModel should then contain a property:
public class Item
{
public string ItemString { get;set; }
}
Try This...
string ListBoxConent = ((ListBoxItem)listbox.SelectedItem).Content.ToString();
Try
listBox.SelectedItem.ToString()
If a property isn't specified in ValueMember then SelectedValue returns the results of the ToString method of the object.

Categories

Resources