WPF Set Text to TextBlock for selected List Item in VB.NET
In this article you will learn that how you can select Item from ListBox and also set Text to TextBlock for selected List Item.
Introduction
Here in this article we are discussing that how you can set text to TextBlock for selected list item. When you select any item from ListBox. MessageBox will show the Selected item, as well as you can enter Text to TextBlock for selected list item and clicking on controls and items you can see which control wrapped the another control. The implementation of example needs ListBox, StackPanel, TextBox, TextBlock and a Button control.
Getting Started
- Simply create a new WPF application.
- Drag a StackPanel, TextBlock, TextBox, ListBox, Label and a Button Control on MainWindow. The Window will look like below.
- Your MainWindow.xaml page will look like below.
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="338" Width="297">
<StackPanel>
<ListBox SelectionChanged="External_SelectionChanged" Name="ExternalListBox">
<ListBoxItem Content="Language 1" FontFamily="Vardana" HorizontalContentAlignment="Left" />
<ListBoxItem Content="Language 2" FontFamily="Arial" FontSize="16"
HorizontalContentAlignment="Center" />
<ListBoxItem Content="Language 3" FontSize="20" HorizontalContentAlignment="Right" />
<Button Content="Button Direct in List" Margin="5" />
<ListBoxItem HorizontalContentAlignment="Center" Margin="5">
</ListBoxItem>
<ListBox Height="50" Margin="5">
<ListBoxItem Content="ASP.NET" Selected="ListBoxItem_Selected" />
<ListBoxItem Content="VB.NET" Selected="ListBoxItem_Selected" />
<ListBoxItem Content="WPF" Selected="ListBoxItem_Selected" />
<ListBoxItem Content="SILVERLIGHT" Selected="ListBoxItem_Selected" />
</ListBox>
<StackPanel Margin="5" Orientation="Horizontal">
<Label Content="Plese enter Text:" />
<TextBox MinWidth="150" />
</StackPanel>
</ListBox>
<TextBlock Text="You Have not selected any language." Margin="10" HorizontalAlignment="Center"
Name="txtSelectedItem" />
</StackPanel>
</Window>
- Then attach the below code in code behind file.
Private Sub ListBoxItem_Selected(sender As Object, e As RoutedEventArgs)
Dim Listitem As ListBoxItem = TryCast(e.OriginalSource, ListBoxItem)
If Listitem IsNot Nothing Then
MessageBox.Show(Convert.ToString(Listitem.Content) & " Item was selected.", Title)
End If
End Sub
Private Sub ExternalListBox_SelectionChanged(sender As Object, e As SelectionChangedEventArgs)
Dim Litem As Object = ExternalListBox.SelectedItem
If Litem Is Nothing Then
txtSelectedItem.Text = "Currently you dont have selected any Item."
Else
txtSelectedItem.Text = Litem.ToString()
End If
End Sub
- Now run your application.
Output:-
Summary
In this article you learned that how you can select the Items from ListBox and also set Text to TextBlock.