Reputation: 3553
In WinRT XAML I have a ComboBox
which displays some complex item.
Is it possible to declare and bind two different item templates for 1) the "normal" selected item (ComboBox is closed) and 2) the list in the Popup when the user wants to choose another item (ComboBox is open)?
I found ItemTemplate
to work for both, but I want to display the items with a slightly different template if the user wants to choose another item.
Upvotes: 0
Views: 1108
Reputation: 4885
Use Item Template Selector. Define two properties SelectedTemplate and DropDownTemplate in Selector class. Check whether the container is wrapped in a ComboboxItem. If yes choose DropDownTemplate. If not choose SelectedTemplate.
public class ComboBoxItemTemplateSelector : DataTemplateSelector
{
public DataTemplate SelectedTemplate { get; set; }
public DataTemplate DropDownTemplate { get; set; }
protected override DataTemplate SelectTemplateCore(object item, DependencyObject container)
{
var comboBoxItem = container.GetVisualParent<ComboBoxItem>();
if (comboBoxItem == null)
{
return SelectedTemplate;
}
return DropDownTemplate;
}
}
public static class DependencyObjectExtensions
{
public static T GetVisualParent<T>(this DependencyObject child) where T : FrameworkElement
{
while ((child != null) && !(child is T))
{
child = VisualTreeHelper.GetParent(child);
}
return child as T;
}
}
ComboBox in XAML,
<Page.Resources>
<local:ComboBoxItemTemplateSelector x:Key="selector">
<local:ComboBoxItemTemplateSelector.DropDownTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding ID}"/>
<TextBlock Text="{Binding Name}" Margin="5 0 0 0"/>
</StackPanel>
</DataTemplate>
</local:ComboBoxItemTemplateSelector.DropDownTemplate>
<local:ComboBoxItemTemplateSelector.SelectedTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}"/>
</StackPanel>
</DataTemplate>
</local:ComboBoxItemTemplateSelector.SelectedTemplate>
</local:ComboBoxItemTemplateSelector>
</Page.Resources>
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<ComboBox x:Name="combo"
ItemTemplateSelector="{StaticResource selector}">
</ComboBox>
</Grid>
Upvotes: 5