Skip to main content
Home Forums Silverlight Programming Programming with .NET - General Bind ListBoxItem to XAML snippet
3 replies. Latest Post by Allen Chen – MSFT on September 8, 2008.
(0)
devingoble
Member
5 points
8 Posts
09-06-2008 1:56 AM |
I have a collection of objects that have a property that contains a snippet of XAML. Is it possible to bind a ListBox to that collection so that the XAML is rendered in the ListBoxItems?
Thanks
BoloRamji
338 points
49 Posts
09-08-2008 1:08 AM |
Please bear with me if I have not understood your problem. There may be other solutions possible and I have enclosed my solution below:
Here is the main page ( Page.xaml)
<
</
Page.xaml.cs
using
{
AddObjectWithXAML();
InitializeComponent();
myImageList.ItemsSource = mObjectList;
}
mObjectList.Add(pObject1);
EllipseXAML +=
mObjectList.Add(pObject2);
XAML = szXAML;
List<MyObject> mObjectList = new List<MyObject>();
You can replace the above two classes and following two lines with the ObjectList you have.
Now, the custom control which takes care of drawing the elements in a separate file MyControl.cs
source.PerformLayout(e.NewValue.ToString());
Important thing here to note in the DependencyProperty which I have defined for MyData which is linked to XAML data of the MyObject which is refered in Page.XAML. Beuatiful thing about this DependencyProperty is you can do any element rendering as it is assigned ( I am using the NewValue member to draw the element above).
You can replace the MyObject with your object that contain your info.
Hope that helps.
Allen Ch...
Star
13862 points
1,803 Posts
09-08-2008 5:41 AM |
Hi
Please try this:
<ListBox Width="200" Height="200" x:Name="ListBox1"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel Loaded="StackPanel_Loaded"></StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox>
public partial class Page : UserControl { List<string> array = new List<string>(); public Page() { InitializeComponent(); string textbox = @"<TextBox xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' Text='Hello'/>"; string textblock = @"<TextBlock xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' Text='World'/>"; array.Add(textbox); array.Add(textblock); this.ListBox1.ItemsSource = array; }
private void StackPanel_Loaded(object sender, RoutedEventArgs e) { StackPanel sp = (StackPanel)sender; sp.Children.Add((UIElement)XamlReader.Load(sp.DataContext.ToString())); }