【问题标题】:Different item templates in ComboBoxComboBox 中的不同项目模板
【发布时间】:2013-05-23 12:23:12
【问题描述】:

在 WinRT XAML 中,我有一个 ComboBox,它显示了一些复杂的项目。

是否可以声明和绑定两个不同的项目模板:1)“正常”选定项目(ComboBox 已关闭)和 2)当用户想要选择另一个项目时 Popup 中的列表(ComboBox 已打开)?

我发现ItemTemplate 对两者都适用,但如果用户想选择另一个项目,我想用稍微不同的模板显示这些项目。

【问题讨论】:

    标签: xaml windows-runtime winrt-xaml


    【解决方案1】:

    使用项目模板选择器。在 Selector 类中定义两个属性 SelectedTemplate 和 DropDownTemplate。检查容器是否包装在 ComboboxItem 中。如果是,请选择 DropDownTemplate。如果没有选择 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;
        }
    }
    

    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>
    

    【讨论】:

    • 简洁明了(XAML 也可以)
    猜你喜欢
    • 1970-01-01
    • 2013-09-12
    • 2011-06-08
    • 1970-01-01
    • 2014-03-13
    • 1970-01-01
    • 1970-01-01
    • 2016-01-20
    相关资源
    最近更新 更多