This is a migrated thread and some comments may be shown as answers.

Select a node from code-behind

24 Answers 580 Views
TreeView
This is a migrated thread and some comments may be shown as answers.
Jonathan Miller
Top achievements
Rank 1
Jonathan Miller asked on 17 Sep 2008, 02:00 PM
Hi

TreeView for Silverlight, how do you select a node from code-behind?

24 Answers, 1 is accepted

Sort by
0
Valentin.Stoychev
Telerik team
answered on 17 Sep 2008, 07:09 PM
Hello Jonathan,

Use the IsSelected property of the RadTreeViewItem to set the selected state.

Kind regards,
Valentin.Stoychev
the Telerik team

Check out Telerik Trainer, the state of the art learning tool for Telerik products.
0
Jonathan Miller
Top achievements
Rank 1
answered on 18 Sep 2008, 06:35 PM
Thank you Valentin.

The ItemsSource is a List<> from a WCF service

Here is my error:

Unable to cast object of type 'pcsSilverlight.pcsServiceReference.Folders' to type 'Telerik.Windows.Controls.RadTreeViewItem'.

I am trying, but I am sure missing something simple.

here is the code:
radTree.ItemsSource = e.Result;  
radTree.DisplayMemberPath = "FolderName";  
radTree.SelectedValuePath = "ID";  
 
RadTreeViewItem itm = (RadTreeViewItem)radTree.Items[0];  
itm.IsSelected = true

How should I cast this to select node [0] in code behind? Thank you

0
Accepted
Valentin.Stoychev
Telerik team
answered on 19 Sep 2008, 07:10 AM
Hello Jonathan,

to get a reference to the container of the TreeViewItem use the following syntax:

RadTreeViewItem itm = radTree.ItemContainerGenerator.ContainerFromIndex(0) as RadTreeViewItem;


Kind regards,
Valentin.Stoychev
the Telerik team

Check out Telerik Trainer, the state of the art learning tool for Telerik products.
0
Tim
Top achievements
Rank 1
answered on 08 Oct 2008, 07:42 AM

Hi Valentin,

I'm struggling with the same problem.
I have a tree with databound items. My itemssource is set to an IEnumerable<object>.
When I drop an item onto another item, I want to be able to select this dropped item (a child item, can be anywhere & on all levels in the tree).
I tried using the method you proposed, and also found info in another thead on the forum.

But this line "RadTreeViewItem itm = radTree.ItemContainerGenerator.ContainerFromIndex(0) as RadTreeViewItem;" always returns null, whatever I do with it.
Is this an issue in RC0? Or can it be related to the objects I bind to the tree?

Kind regards,

Tim Plessers

0
Valentin.Stoychev
Telerik team
answered on 08 Oct 2008, 09:50 AM
Hi Tim ,

Check this example:
http://demos.telerik.com/silverlight/#Examples/TreeView/AccessingItems

It is working by using the methods you are mentioning, so the problem should be different. If you want - send me a simple project and we'll take a look at it.


Sincerely yours,
Valentin.Stoychev
the Telerik team

Check out Telerik Trainer, the state of the art learning tool for Telerik products.
0
Tim
Top achievements
Rank 1
answered on 10 Oct 2008, 05:44 AM
Hi Valentin,

I'll take a closer look on that demo & on our code.

Thanks,

Tim Plessers
0
Jonathan Miller
Top achievements
Rank 1
answered on 25 Oct 2008, 01:35 AM
btw: this is working perfect after RC0, thanks!
0
Jonathan Miller
Top achievements
Rank 1
answered on 25 Oct 2008, 02:58 AM
sorry, rc1, still having issues - looks like it works in your example, but from code-behind - before the page renders on the first load, continues to show as null items
0
Valentin.Stoychev
Telerik team
answered on 25 Oct 2008, 07:52 AM
Hello Jonathan Miller,

In which moment you are trying to access the child items? Code sample will be of great help?

Kind regards,
Valentin.Stoychev
the Telerik team

Check out Telerik Trainer, the state of the art learning tool for Telerik products.
0
Jonathan Miller
Top achievements
Rank 1
answered on 25 Oct 2008, 02:07 PM
Hi Valentin

Here is the order:

My app loads > on successful login, the app loads user items from WCF List<> (including folder treeview). Upon completed load of the List<> from WCF, the treeview thinks there are no items in it, but my item source has items and will display them in the tree.  

I simply can't select an item (IsSelected=true;) in the tree from code-behind.  Thank you for reviewing

XAML:
<telerik:RadTreeView x:Name="treeMailFolders" ItemsSource="{Binding}" SelectionChanged="treeMailFolders_SelectionChanged"></telerik:RadTreeView> 

Coming from WCF:
[DataContract] 
    public class Folders 
    { 
        [DataMember] 
        public string FolderName; 
        [DataMember] 
        public int ID; 
        [DataMember] 
        public int ParentFolderID; 
    } 

Code behind:

treeMailFolders.ItemsSource = e.Result; 
treeMailFolders.DisplayMemberPath = "FolderName"
treeMailFolders.SelectedValuePath = "ID";
RadTreeViewItem itm = treeMailFolders.ItemContainerGenerator.ContainerFromIndex(0) 
as RadTreeViewItem; 
 if (itm != null
                { 
                    itm.IsSelected = true
                } 
 
ctedValuePath = "ID"
0
Accepted
Valentin.Stoychev
Telerik team
answered on 26 Oct 2008, 02:47 PM
Hello Jonathan,

this code:
treeMailFolders.ItemsSource = e.Result; 
treeMailFolders.DisplayMemberPath = "FolderName"
treeMailFolders.SelectedValuePath = "ID";
RadTreeViewItem itm = treeMailFolders.ItemContainerGenerator.ContainerFromIndex(0) 
as RadTreeViewItem; 
 if (itm != null
                { 
                    itm.IsSelected = true
                }

will not work because the generation of the items is asyncronous event. This is done by the Silverlight framework. Please use the code below
            treeMailFolders.ItemsSource = e.Result;  
            treeMailFolders.DisplayMemberPath = "FolderName";  
            treeMailFolders.SelectedValuePath = "ID";  
            treeMailFolders.ItemContainerGenerator.StatusChanged += new EventHandler(ItemContainerGenerator_StatusChanged);  
        ....
        ....
 
        void ItemContainerGenerator_StatusChanged(object sender, EventArgs e)  
        {  
            if (RadTreeView1.ItemContainerGenerator.Status == Telerik.Windows.Controls.Primitives.GeneratorStatus.ContainersGenerated)  
            {  
                RadTreeViewItem itm = treeMailFolders.ItemContainerGenerator.ContainerFromIndex(0) as RadTreeViewItem;  
                if (itm != null)  
                {  
                    itm.IsSelected = true;  
                }  
            }  
        }  
 


This code will handle the StatusChanged event of the ItemContainerGenerator and once the items are generated you can safely access them.


Greetings,
Valentin.Stoychev
the Telerik team

Check out Telerik Trainer, the state of the art learning tool for Telerik products.
0
Chad
Top achievements
Rank 1
answered on 21 Nov 2008, 10:48 PM
Hi,
I'm having some troubles getting a Node By Item, it keeps returning a Null value, probably because it cannot find the item, however I get the item directly from the tree.

Here is the code:

C#:

void CheckedItems_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
         

            LinkedList<string>[] checkedNodes = new LinkedList<string>[3];

            

            TreeArea area = new TreeArea();


            for (int i = 0; i < checkedNodes.Length; i++)
            {
                checkedNodes[i] = new LinkedList<string>();
            }
           
            
            foreach (object item in treeWells.CheckedItems)
            {
                if (item.ToString().Equals("WTXNetSilver.TreeArea"))
                {
              
                   RadTreeViewItem view = treeWells.ItemContainerGenerator.ContainerFromItem(item) as RadTreeViewItem;

                }
}
}

view ends up being NULL when I try to get with item, but it returns a value when I try to get it with index.

Any suggestions?

Thanks,
Chad

0
Ivan
Telerik team
answered on 01 Dec 2008, 07:58 AM
Hi Chad,

Please try with the RadTreeView.ContainerFromItemRecursive method instead of the tree.ItemContainerGenerator.ContainerFromItem one.

Let me know if this helps.

All the best,
Ivan
the Telerik team

Check out Telerik Trainer, the state of the art learning tool for Telerik products.
0
Bichitra
Top achievements
Rank 1
answered on 04 Dec 2008, 03:00 AM
HI,

I am getting same problem. But aother issue is

I did  the following steps..

I have create cutome TreeviewItem inherits from RadTreeviewitem. and assign header propety to textblock.
but when i am getting My custome treeviewItem as textBlock. I did not understand how it converted to TextBlock at runtime.

as  i am trying to select that treeview Item , it is not selected and selected  event is not fired.

treeViewAddress.ItemContainerGenerator.ContainerFromItem(childItem)


Can u help,Please to fix this issue?

Thanks
Bichitra
0
Hristo
Telerik team
answered on 04 Dec 2008, 08:50 AM
Hi Bichitra,

RadTreeViewItem override ToString method and returns header.ToString(). This is why you see it like textBlock.

We were unable to reproduce your problem.
Can you provide us with sample code where the selected event is not fire?


Sincerely yours,
Hristo
the Telerik team

Check out Telerik Trainer, the state of the art learning tool for Telerik products.
0
Bichitra
Top achievements
Rank 1
answered on 04 Dec 2008, 07:34 PM
Hi ,

I am using 2008.3.1117.1020 version control.

Sample I did.

Public class MyTreeviewItem : RadTreeViewItem
{
}
public class  MyTreeview : RadTreeview
{
}

public class MyClass
{

private void FillTreeView()
{
 MyTreeviewItem  parentNode1 = new MyTreeviewItem ();
parentNode1.IsExpanded =true;
parentNode2.IsExpanded =true;
MyTreeviewItem  parentNode2 = new MyTreeviewItem();
MyTreeViewObj.Add(parentNode1);
MyTreeViewObj.Add(parentNode2);
MyTreeviewItem childItem;
TextBlock tb;
    foreach (item in ItmelIst)
    {
        childItem = new MyTreeviewItem();
        childItem.Selected += new EventHandler<Telerik.Windows.RadRoutedEventArgs>(ChildItem_Selected);
        tb = new TextBlock();
        tb.Text = "Test";
        childItem.Header = tb;
          childItem.Tag = item;
     if ( condition)
     {
        parentNode1.Items.Add(childItem);
      }
     else
     {
       parentNode2.Items.Add(childItem);
     }
       
    }
  // finaly I am trying to select   childItem . It  is not selected and doesnt fire the event aslo.
}

}

I was trying to remove textblock control and direct set string to header. and used to get treeviewItem using the ways mentioned in this post. but still item is coming null (radTree.ItemContainerGenerator.ContainerFromIndex/ContainerFromItem ) .

Can you please help to fix this isuues.

Thanks
Bichitra
0
Miroslav
Telerik team
answered on 08 Dec 2008, 05:30 PM
Hello Bichitra,

Generally, we do not encourage inheriting the controls unless of the extreme case where functionality is missing and there is no straightforward way to get the desired result.

When you set the header of a TreeViewItem to a String the HeaderTemplate is automatically set to a TextBlock anyway. Then, managing and testing the application is much easier when the items are bound and you do not have to worry about syncronizing them.

Getting the TreeView items may seem difficult but this is simply because Silverlight is creating them in a lazy way, only when they are needed. This is somewhat more difficult to achieve if you are managing the creation of the items.

The TreeView would not return the items before they are created and they will not be created before they are needed.

You can force the items to expand by calling the ExpandAll() method. This of course is not recommended for large number of items.

Then you can handle the ItemPrepared event and wait for the TreeView item to be generated.

You can also expand the items inside the ItemPrepared event and stop expanding them once you find the right container:


void treeView_ItemPrepared(object sender, RadTreeViewItemPreparedEventArgs e)  
        {  
            if (!selectionSuccessful)  
            {  
                if (e.PreparedItem.DataContext == selectedItem)  
                {  
                    e.PreparedItem.IsSelected = true;  
                    selectionSuccessful = true;  
                }  
                else 
                {  
                    e.PreparedItem.IsExpanded = true;  
                }  
            }  
        } 


I am attaching a sample solution where together with more advanced features, the selection is presented as well.

Does that work for you?

Greetings,
Miroslav
the Telerik team

Check out Telerik Trainer, the state of the art learning tool for Telerik products.
0
Chad
Top achievements
Rank 1
answered on 17 Dec 2008, 09:57 PM
Hi Ivan,

I just tried out the RadTreeView.ContainerFromItemRecursive but I still get a null value for the item. 

Here is the code now:

foreach

(object item in treeWells.CheckedItems)

 

{

 

if (item.ToString().Equals("WTXNetSilver2.TreeArea"))

 

{

 

RadTreeViewItem treeview = treeWells.ContainerFromItemRecursive (item) as RadTreeViewItem;

.... other non-important code here

}
}

any more suggestions on how I can fix this?

0
Chad
Top achievements
Rank 1
answered on 17 Dec 2008, 10:10 PM
Alright, I fixed it.

    

 

TreeArea area = new TreeArea();

 

 

 

foreach (object item in treeWells.CheckedItems)

 

{

 

if (item.ToString().Equals("WTXNetSilver2.TreeArea"))

 

{

 

treeItem = (

RadTreeViewItem)item;

 

area = (

TreeArea)treeItem.Item;

}

}

from there, I can access all of area's variables.  Seems very impracticle to have to do it this way, but it may be for security reasons.  I'm not too experienced at web programming.

 

0
malebo
Top achievements
Rank 1
answered on 04 Feb 2009, 07:24 AM

Hi,

 

My selected item does not seem to get highlighted as selected. when i use IsSelected programmatically.

 

Is this familiar problem? Or it is just me

0
Tihomir Petkov
Telerik team
answered on 04 Feb 2009, 07:46 AM
Hi malebo,

Must be something on your end - everything seems to work here. Check the attached project.

Regards,
Tihomir Petkov
the Telerik team

Check out Telerik Trainer, the state of the art learning tool for Telerik products.
0
malebo
Top achievements
Rank 1
answered on 04 Feb 2009, 10:27 AM
Thanks. You right it works fine. It was on my side.

I would like to change the style of the seleted item on the template. Which template will be right to change
 
I know the question of mofiying template was asked somewhere on the forum. just can't find it
0
Tihomir Petkov
Telerik team
answered on 04 Feb 2009, 10:44 AM
Hi malebo,

I'm attaching a project that contains the complete control template of RadTreeViewItem. To modify the selected state just play with the corresponding visual state in the template.

Greetings,
Tihomir Petkov
the Telerik team

Check out Telerik Trainer, the state of the art learning tool for Telerik products.
0
malebo
Top achievements
Rank 1
answered on 04 Feb 2009, 02:17 PM
Thank you Tihomir
Tags
TreeView
Asked by
Jonathan Miller
Top achievements
Rank 1
Answers by
Valentin.Stoychev
Telerik team
Jonathan Miller
Top achievements
Rank 1
Tim
Top achievements
Rank 1
Chad
Top achievements
Rank 1
Ivan
Telerik team
Bichitra
Top achievements
Rank 1
Hristo
Telerik team
Miroslav
Telerik team
malebo
Top achievements
Rank 1
Tihomir Petkov
Telerik team
Share this question
or