Introduction In my previous article on TreeView titled “Tree View In Silverlight 3 Application”; we explored a simple TreeView with some Parent and Child Nodes. In this article we will see how can we select the Node name and display which node you have selected.
Creating Silverlight Project Fire up Visual Studio 2008 and create a Silverlight Application. Name it as TreeViewSL3.

Open the solution in Expression Blend 3. Go ahead and a Tree View control to your application. I have changed the Background to Linear Brush. To add TreeView Item to the Tree View, just right click on it and add TreeViewItem.

Add several, and if you want to add children of any parent then select the particular TreeViewItem and add another Treeview Item. I have created the below hierarchy:

If you see the design view it will look similar to the following:

Here is the XAML code behind for the TreeView: {codecitation class="brush: xml; gutter: true;" width="700px"}
{/codecitation} Now we will add a TextBlock which will display which node is been selected. Follow the Xaml code:
{codecitation class="brush: csharp; gutter: true;" width="700px"}
{/codecitation}
We can achieve the objective in both XAML code and C# code. For the time being I will use the C# code behind. Add an event SelectedItemChanged for the TreeView.
{codecitation class="brush: csharp; gutter: true;" width="700px"}
SelectedItemChanged="MyTreeView_SelectedItemChanged"
{/codecitation}
Now navigate to the Event Handler and add the following code:
{codecitation class="brush: csharp; gutter: true;" width="700px"}
private void MyTreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs e) { TreeView view = sender as TreeView;
if (view != null) { SelectedValue.Text= (view.SelectedItem as TreeViewItem).Header.ToString(); } }
{/codecitation} As you see from the above code I have created an instance of the TreeView and if it’s value us not null; I am typecasting the object to a TreeViewItem. Then using the Header property I am assigning it to a TextBlock’s Text property. If you run your application you can see the change: 
That’s it, it was so simple to achieve that. Enjoy Coding.
| About the Author |
 | | Diptimaya Patra | Description :I am a Master in Computer Application (MCA) from SRM University, Chennai. I am MCTS in ASP.Net Web Development, and MOSS 2007 Administration. I have extreme exposure to Microsoft Technologies in recent times like Silverlight 2, Silverlight 3. I am from Cuttack, Orissa. You can reach me using this mail (diptimaya.patra@gmail.com). Currently I am working as a Software Engineer in UST Global Inc in Trivandrum Center.
Occupation :Software Engineer Company : UST Global. Location : India Follow me at twitter : http://twitter.com/dpatra
|
|
|