I have a user control that displays objects of a client-declared type with some specialized behavior. I would like to use generics. However, I’m not sure how to declare this in the XAML:
<local:EditableListBox x:Name="SectionList" Margin="56,8,15,0" FontSize="64" SelectionChanged="SectionList_SelectionChanged" />
ListBox uses object members, which makes me think that perhaps there’s no way to have type safety here. Or is there?
(I’m building a Windows Phone 7 app, if it makes any difference.)
Update: I’m totally fine with not having generics in the XAML, but I’m still trying to figure out how to set it up in the code-behind. I parameterized everything, but it’s still complaining.
Code behind:
public partial class EditableListBox<T> : UserControl, INotifyPropertyChanged where T : IEditableListMember {
public EditableListBox()
{
// Error: The name 'InitializeComponent' does not exist in the current context
InitializeComponent();
Loaded += new RoutedEventHandler(EditableListBox_Loaded);
}
// ...
public int SelectedIndex
{
get
{
// Error: The name 'ContentListBox' does not exist in the current context
return ContentListBox.SelectedIndex;
}
set
{
// Error: The name 'ContentListBox' does not exist in the current context
ContentListBox.SelectedIndex = value;
}
}
The XAML:
<Grid x:Name="LayoutRoot">
<ListBox x:Name="ContentListBox">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid ManipulationCompleted="Grid_ManipulationCompleted">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Image Source="{Binding IconSource}"
Grid.Column="0"
Width="96"
Height="96"
VerticalAlignment="Center"
Visibility="{Binding Editing, Converter={StaticResource visibilityConverter}}"
/>
<TextBlock Text="{Binding Name}"
Grid.Column="1"
Foreground="{Binding Enabled, Converter={StaticResource enabledConverter}}" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
It gives two compiler errors: the ListBox ContentListBox and InitializeComponent() are not defined. I suspect that the problem has something to do with how the class is split into two partial definitions, and mine is parameterized whereas the generated code is not. How can I get around this?
No you can’t use generic types in Silverlight XAML directly.
But you could familiarize yourself with the MVVM pattern. Your models and viewmodels can easily be generic types, and you can do all your coding there. The XAML views are dumb, have no or few code behind, and only bind to the view models.