2

この単純な XAML の例があります。

<Window x:Class="DynTemplateTest.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">

    <Window.Resources>
        <DataTemplate x:Key="ItemTemplate">
            <ItemsControl ItemsSource="{Binding}">
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <Rectangle Width="30" Height="30" Fill="Red"></Rectangle>                        
                    </DataTemplate>
                </ItemsControl.ItemTemplate>  
                <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <Canvas />
                    </ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>
                <ItemsControl.ItemContainerStyle>
                    <Style>
                        <Setter Property="Canvas.Left" Value="{Binding Position}"></Setter>
                    </Style>
                </ItemsControl.ItemContainerStyle>
            </ItemsControl>
        </DataTemplate>
    </Window.Resources>

    <DockPanel LastChildFill="True">
        <ContentPresenter
            Content="{Binding Path=Items}"
            ContentTemplate="{StaticResource ItemTemplate}"
            >
        </ContentPresenter>
    </DockPanel>

</Window>

MVVM スタイルの観察可能なコレクションでアイテムをレンダリングしています。各アイテムは、プロパティ内で水平位置を持っています。各アイテムには IsSpecial プロパティもあり、特別な方法でレンダリングする必要があるかどうかを示します。通常のアイテム (IsSpecial=false) を赤い四角 (既にコード内にある) としてレンダリングし、特別なアイテムを「特別な」テキストを含む青い円としてレンダリングします。

私が知らないのは、アイテムのテンプレート選択を行うために XAML コードを調整する方法です。自分の ItemTemplateSelector をコーディングせずにそれを行う方法はありますか? バインディングに基づいたキャンバスの配置でも機能しますか。解決策は、アイテム テンプレートを別のテンプレートに抽出し、特別なアイテム用のテンプレートをもう 1 つ作成してから、何らかの方法でトリガーを操作することだと思いますが、現時点では WPF 初心者であるため、簡単ではありません。

もう 1 つは、Position がアイテムに渡される方法が非常に気に入らないことです。他の方法はありますか?

コードを改善するための他の推奨事項はありますか?

4

1 に答える 1