Reputation: 10463
I want to bind list of objects each of it has UIType (ie textbox, checkbox, combo etc). And it has object Value property.
I want to bind this list to an ItemControl (ListBox, DataGrid..) where each item will have separate template corresponding to the particular UIType of each object (eg item for combo will have combo in the row and item for checkbox will have checkbox)...
obviously prop Value will be bound to relevant property on each item.
whats the most transparent and not too elaborate way to achieve this?
Silverlight 5.
EDIT: (working code based on the Jacob's solution)
code:
ObservableCollection<UIType> data;
public MainPage()
{
InitializeComponent();
data = new ObservableCollection<UIType>()
{
new UITypeTextBox() { Value = "Value.." },
new UITypeCheckBox(){ Value = true },
};
lb.ItemsSource = data;
}
public class UIType { }
public class UITypeTextBox : UIType { public object Value { get; set; }}
public class UITypeCheckBox : UIType { public object Value { get; set; } }
xaml:
<ListBox x:Name="lb">
<ListBox.Resources>
<DataTemplate DataType="local:UITypeTextBox">
<TextBox Text="{Binding Value}" />
</DataTemplate>
<DataTemplate DataType="local:UITypeCheckBox">
<CheckBox IsChecked="{Binding Value}" />
</DataTemplate>
</ListBox.Resources>
</ListBox>
Upvotes: 1
Views: 762
Reputation: 14956
I am not sure about Silverlight but in WPF you can use data templates to do this. For each of your UI types you define a data template which basically maps a type to a view which is just a user control defined i XAML.
Typically you will define the data templates in a resource dictionary:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:views="clr-namespace:MyApp.Views"
xmlns:uitypes="clr-namespace:MyApp.UITypes"
>
<DataTemplate DataType="{x:Type uitypes:TextBox}">
<views:TextBoxView />
</DataTemplate>
<DataTemplate DataType="{x:Type uitypes:CheckBox}">
<views:CheckBoxView />
</DataTemplate>
</ResourceDictionary>
Your views would be XAML files inheriting from UserControl. For example the XAML for the TextBox view might look like the following.
<UserControl x:Class="MyApp.Views.TextBox"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
<Grid>
<TextBox Text="{Binding Value}" />
</Grid>
</UserControl>
WPF (and hopefully Silverlight) automatically pics the right view when you add your UI types to an ItemControl.
Upvotes: 2