TreeView double click event - c#

I want to define a double click even on a TreeView so that I will be able to know which item in the TreeView was selected and to get his title.
The way I try to get it's title gets me "MyProject.MenuItem".
How can I refer to the selected item on the tree, make sure it's not the root, and get it's title?
What I did:
<TreeView Name="trvMenu" HorizontalAlignment="Left" Height="312" VerticalAlignment="Top" Width="200" MouseDoubleClick="TreeView_MouseDoubleClick" >
<TreeView.ItemTemplate>
<HierarchicalDataTemplate DataType="{x:Type local:MenuItem}" ItemsSource="{Binding Items}">
<TextBlock Text="{Binding Title}" />
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
The MessageBox shows "MyProject.MenuItem", what I want to do is not show a messagebox, but to get the title of the selected treeview item, after checking it is not the root
private void TreeView_MouseDoubleClick(object sender, RoutedEventArgs e)
{
if (sender is TreeViewItem)
if (!((TreeViewItem)sender).IsSelected)
return;
TreeViewItem tviSender = sender as TreeViewItem;
MessageBox.Show(trvMenu.SelectedItem.ToString());
}

Change your double click handler like shown below. Instead of calling ToString it accesses the Title property of your MenuItem item class.
private void TreeView_MouseDoubleClick(object sender, RoutedEventArgs e)
{
var menuItem = trvMenu.SelectedItem as MyProject.MenuItem;
if (menuItem != null)
{
MessageBox.Show(menuItem.Title);
}
}

Related

Get textBlock text that is inside a datatemplate from C# (XAML)

i want to do some coding on textblock tap event for which, i required its text value
my xaml is like below
<ListBox x:Name="listBox1">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Height="auto" >
<TextBlock Name="myTextBlock" Text="{Binding Busnumber}" Tap="buss_Tap" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
and then on textblock tap event i want to get tapped clicked text value
private void buss_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
//i want to achieve this
// string aa= myTextBlock.text;
//but this is not working so what to do here to achieve the same?
}
Try this:
private void buss_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
TextBlock txt = (TextBlock)sender;
MessageBox.Show(txt.Text);
}
You will get TextBlock in sender parameter. Typecast it to Textblock and can get text from there:
string text = ((TextBlock)sender).Text;

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);
}

Get items values of ListBox with SelectedIndex

I've got for example ListBox with two TextBlocks like this:
<ListBox Name="listboxNews"
SelectionChanged="listboxNews_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Width="400"
Height="70">
<TextBlock Text="{Binding Title}" name="title" />
<TextBlock Text="{Binding Description}" name="desc" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
And as you can see, I've got listboxNews_SelectionChanged method, in which i need to select Text of first TextBlock (if posibble by name so it will be independent on order of textblocks), but this one, which I select. For example if first item has title "Item 1" and second "Item 2" and I click on second one, i need to get "Item 2". I was trying something with listboxNews.Items, but i guess this is not correct. Thanks for help.
The SelectedItem property will hold the currently selected object. You can just cast that and take the Title property.
Try this code:
private void listboxNews_SelectionChanged(object sender, SelectionChangedEventArgs e) {
var current = listboxNews.SelectedItem as MyObjectType;
MessageBox.Show(current.Title);
}
Change MyObjectType with the type of your object.
This is a copy and paste out of a working Windows Phone 8 solution.
This was also tested successfully in WPF.
private void ListBox_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
{
foreach (UIElement item in (sender as ListBox).Items)
{
if ((sender as ListBox).SelectedItem == item)
{
foreach (UIElement InnerItem in (item as StackPanel).Children)
{
if ((InnerItem is TextBlock) && (InnerItem as TextBlock).Name.Equals("title"))
{
MessageBox.Show((InnerItem as TextBlock).Text);
}
}
}
}
}

How to access an inner ItemsControl in a ListBox in Windows Phone Silverlight

I am building a small Windows Phone application which has a databound ListBox as a main control. DataTemplate of that ListBox is a databound ItemsControl element, which shows when a person taps on a ListBox element.
Currently, I am accessing it by traversing the visual tree of the application and referencing it in a list, and than getting the selected item through SelectedIndex property.
Is there a better or more effective way?
This one works currently, but I am afraid if it would stay effective in case of larger lists.
Thanks
Have you tried wiring the SelectionChanged event of the ListBox?
<ListBox ItemsSource="{Binding}" SelectionChanged="ListBox_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<!-- ... -->
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
With this in the code behind:
private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListBox listBox = sender as ListBox;
// nothing selected? ignore
if (listBox.SelectedIndex != -1)
{
// something is selected
}
// unselect the item so if they press it again, it takes the selection
listBox.SelectedIndex = -1;
}
ListBoxItem item = this.lstItems.ItemContainerGenerator.ContainerFromIndex(yourIndex) as ListBoxItem;
Then you can use the VisualTreeHelper class to get the sub items
var containerBorder = VisualTreeHelper.GetChild(item, 0) as Border;
var contentControl = VisualTreeHelper.GetChild(containerBorder, 0);
var contentPresenter = VisualTreeHelper.GetChild(contentControl, 0);
var stackPanel = VisualTreeHelper.GetChild(contentPresenter, 0) as StackPanel; // Here the UIElement root type of your item template, say a stack panel for example.
var lblLineOne = stackPanel.Children[0] as TextBlock; // Child of stack panel
lblLineOne.Text = "Some Text"; // Updating the text.
Another option is to use services of the GestureServices class available in the WP7 Toolkit.
You'll need to add a GestureListner to the Root Element of your DataTemplate like so:
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<Controls:GestureService.GestureListener>
<Controls:GestureListener Tap="GestureListener_Tap" />
</Controls:GestureService.GestureListener>
<TextBlock x:Name="lblLineOne" Text="{Binding LineOne}" />
<TextBlock Text="{Binding LineTwo}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
And in the GestureListener_Tap event handler, you use this snippet.
private void GestureListener_Tap(object sender, GestureEventArgs e)
{
var itemTemplateRoot = sender as StackPanel;
var lbl1 = itemTemplateRoot.Children[0] as TextBlock;
MessageBox.Show(lbl1.Text);
}
I'm not sure how the GestureListner recognize internally the item being tapped but I guess that it uses the VisualTreeHelper, at least this method is more concise.

How to extract value from selected TextBlock element in a ListBox?

I'm using a ListBox to display all values contained in Dictionary<> object:
<ListBox Height="519" x:Name="ContactsListBox" Width="460" Margin="0,0,0,0" SelectionChanged="ContactsListBox_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding Key}" Margin="5" Foreground="{StaticResource PhoneAccentBrush}"/>
<TextBlock x:Name ="LastNameData" Text="{Binding Value}" Margin="20, 0" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Content is filled by the following code:
Dictionary<long, Contact> contacts = new Dictionary<long, Contact>();
this.ContactsListBox.ItemsSource = contacts;
Now, I would like to 'know' which specific "Contact" in ListBox is currently selected, either by knowing its Key, or just by extracting value from "LastNameData" TextBlock.
I tried doing something like that, but obviosly it doesn't work:
private void ContactsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListBox lb = this.ContactsListBox.SelectedItem as ListBox;
this.Test_SomeOtherTextBlock.Text = lb.ToString();
}
I would really appreciate your help!
you can even do the follwing:
<ListBox Height="519" x:Name="ContactsListBox" Width="460" Margin="0,0,0,0" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding Key}" Margin="5"/>
<TextBlock x:Name ="LastNameData" Text="{Binding Value}" Margin="20, 0" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Grid DataContext="{Binding ElementName=ContactsListBox, Path=SelectedItem}" Margin="0,470,0,0">
<TextBlock Text="{Binding Value}"/>
</Grid>
So you don't need code behind...
BR,
TJ
There are several problems:
In Xaml you probably don't want to display the class name, but a reasonable string, for example:
<TextBlock x:Name ="LastNameData" Text="{Binding Value.LastName}" Margin="20, 0" />
In the selection processing the selected item is KeyValuePair<...>. You could easily find it yourself, if you looked at the returned type in debugger. (Should be kind of a reflex for a programmer, hence a questions like above should never appear :))
private void ContactsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e) {
KeyValuePair<long, Contact> kv = (KeyValuePair<long, Contact>)this.ContactsListBox.SelectedItem;
Contact c = (Contact)kv.Value;
Debug.WriteLine(c.LastName);
}
Your code is good, using ListBox.SelectedItem is the right approach.
I think the problem is that you should cast it as ListBoxItem, not ListBox. And also to get to its value using DataContext, so something like along these lines (not tested, I'm not sure about accessing DataContext value in the last line):
private void ContactsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListBoxItem lbi = this.ContactsListBox.SelectedItem as ListBoxItem;
var dataContext = lbi.DataContext;
this.Test_SomeOtherTextBlock.Text = dataContext.Value.ToString();
}
Try this it works for me, will help you to...
private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListBox ContactListBox = sender as ListBox;
ListBoxItem listBoxItem = ContactListBox .ItemContainerGenerator.ContainerFromItem(ContactListBox.SelectedItem) as ListBoxItem;
if (listBoxItem == null)
{
return;
}
TextBlock txtBlock = FindVisualChildByName(listBoxItem, "ListTextBlock");
MessageBox.Show(txtBlock.Text);
}
private static T FindVisualChildByName<T>(DependencyObject parent, string name) where T : DependencyObject
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
string controlName = child.GetValue(NameProperty) as string;
if (controlName == name)
{
return child as T;
}
T result = FindVisualChildByName<T>(child, name);
if (result != null)
return result;
}
return null;
}
private void ContactsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListBox lb = this.ContactsListBox.SelectedItem as ListBox;
this.Test_SomeOtherTextBlock.Text = lb.ToString();
}
will go something like this..
private void ContactsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListBox lb = this.ContactsListBox.SelectedItem as ListBox;
DataTemplate template=lb.ContentTemplate;
//Now here you have to extract the content of the data template
and then you need to extract the TextBlock from that content.
}
This is just an overview of the functionality.Sorry not able to post complete code.

Categories

Resources