簡體   English   中英

基於畫布的ItemsControl的ItemContainerStyle

[英]ItemContainerStyle for Canvas-based ItemsControl

我有以下ItemsControl,為此我使用了Canvas作為面板:

<ItemsControl ItemsSource="{Binding Widgets}">
    <ItemsControl.Resources>
        <DataTemplate DataType="{x:Type widgetLayoutSpike:ColouredWidget}">
            <Grid Background="{Binding BgColour}">
                <TextBlock Text="{Binding Title}" />
            </Grid>
        </DataTemplate>
    </ItemsControl.Resources>

    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <Canvas />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>

    <ItemsControl.ItemContainerStyle>
        <Style TargetType="ContentPresenter">
            <Setter Property="ContentTemplate">
                <Setter.Value>
                    <DataTemplate>
                        <Grid Background="Yellow">
                            <!--  <ContentPresenter />  -->
                        </Grid>
                    </DataTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </ItemsControl.ItemContainerStyle>
</ItemsControl>

我的要求是:

  • ItemTemplates是通過鍵入的DataTemplates設置的(上面顯示了ColouredWidget項目類型的示例)。 對於不同的項目類型,可能有多個。
  • 我需要能夠指定一個ItemContainer模板,該模板包裝所有不同的ItemTemplates。 具體的用例是我希望此ItemContainer為所有項目(使用按鈕等)設置一個公共邊框鑲邊。

畫布為每個綁定項目創建一個ContentPresenter。 如您在上面看到的,我希望能夠在ItemContainerStyle中為ContentPresenter指定一個ContentTemplate,但這是行不通的,因為我認為它實質上創建了一個循環引用。

提前致謝!

使用ListBox而不是ItemsControl可能更容易做到這一點,因為容器類型是ListBoxItem ,它(與ContentPresenter相比)具有可以在樣式中替換的控件模板:

<ListBox ItemsSource="{Binding Widgets}">
    <ListBox.Resources>
        <DataTemplate DataType="{x:Type widgetLayoutSpike:ColouredWidget}">
            <Grid Background="{Binding BgColour}">
                <TextBlock Text="{Binding Title}" />
            </Grid>
        </DataTemplate>
    </ListBox.Resources>
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="ListBoxItem">
                        <Grid Background="Yellow">
                            <ContentPresenter Margin="2"/>
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>

編輯:也許你必須寫

<ContentPresenter Margin="2"
                  Content="{TemplateBinding Content}"
                  ContentTemplate="{TemplateBinding ContentTemplate}"/>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM