0

WinRT XAML には、ComboBox複雑なアイテムを表示する があります。

1) 「通常の」選択項目 (ComboBox が閉じている) と 2) ユーザーが別の項目を選択したい場合 (ComboBox が開いている) のポップアップのリストに対して、2 つの異なる項目テンプレートを宣言してバインドすることは可能ですか?

両方で機能することがわかりましItemTemplateたが、ユーザーが別のアイテムを選択したい場合は、少し異なるテンプレートでアイテムを表示したいと考えています。

4

1 に答える 1

5

アイテム テンプレート セレクターを使用します。Selector クラスで SelectedTemplate と DropDownTemplate の 2 つのプロパティを定義します。コンテナーが 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>
于 2013-05-23T04:23:12.867 に答える