Silverlight / WPF - binding usercontrol xaml into the listbox

Asked By Ramachandran on 05-Jun-12 04:48 AM
how to bind the usercontrol xaml page into the list box control
TSN ... replied to Ramachandran on 05-Jun-12 04:58 AM

HI..

Here is the sample example which binds user control as list box item

<UserControl x:Class="UseOfListBox.PersonControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Height="Auto" Width="Auto">

<Grid x:Name="LayoutRoot" Background="White">
<
StackPanel DataContext="{Binding}">
<
TextBlock FontFamily="Verdana" Text="{Binding ID}" Margin="0,0,5,0"></TextBlock>
<
TextBlock FontFamily="Verdana" Text="{Binding Name}" Margin="0,0,5,0"></TextBlock>
<
TextBlock FontFamily="Verdana" Text="{Binding Designation}" Margin="0,0,5,0"></TextBlock>
</
StackPanel>
</
Grid>
</
UserControl>

Now we will add this user control as a list box item..

First add the reference and then you can add the control..

xmlns:CustomControl="clr-namespace:UseOfListBox".

<ListBox.ItemTemplate>
<
DataTemplate>
<
CustomControl:PersonControl />
</
DataTemplate>
</
ListBox.ItemTemplate>

Now we can bind the data as simple as done

List<Person> personList = new List<Person>() {
new Person{ ID = 1, Name="acs", Designation="fds"},
new Person{ ID = 2, Name="sasd", Designation="fsd"},
new Person{ ID = 3, Name="dsf", Designation="fds"},

personListBox.ItemsSource = personList;

Neha Garg replied to Ramachandran on 05-Jun-12 05:06 AM

 

Hi Ramachandran

See the below Solution or Example:

xaml

<ListBox x:Name="personListBox" Height="241" HorizontalAlignment="Left" Margin="42,24,0,0" VerticalAlignment="Top" Width="280" >
<
ListBox.ItemTemplate>
<
DataTemplate>
<
StackPanel >
<TextBlock FontFamily="Verdana" Text="{Binding ID}" Margin="0,0,5,0"></TextBlock>
<
TextBlock FontFamily="Verdana" Text="{Binding Name}" Margin="0,0,5,0"></TextBlock>
<
TextBlock FontFamily="Verdana" Text="{Binding Designation}" Margin="0,0,5,0"></TextBlock>
</
StackPanel>
</
DataTemplate>
</
ListBox.ItemTemplate>

Xaml.cs


public class Person
{
public int ID { get; set; }
public string Name { get; set; }
public string Designation { get; set; }
}

Finally bind the data to the list box like this:

List<Person> personList = new List<Person>() {
new Person{ ID = 1, Name="ABC", Designation="Developer"},
new Person{ ID = 2, Name="DEF", Designation="Test Engineer"},
new Person{ ID = 3, Name="GHI", Designation="Support Engineer"}};

personListBox.ItemsSource = personList;