簡體   English   中英

使用ContentPresenter和ItemsPresenter進行自定義控件

[英]Custom control with both ContentPresenter and ItemsPresenter

我建立了一個自定義控件,該控件具有兩個內容區域,如下所示:

+-------------+
| L |         |
| o |  Main   |
| g | Content |
| o |         |
+---+---------+
| Interaction |
+-------------+

我是通過繼承Control並添加兩個依賴項屬性MainContentUserInteractions 使用控件時,我會執行以下操作:

<controls:ScreenControl>
    <controls:ScreenControl.MainContent>
        <TextBlock>Some content goes here</TextBlock>
    </controls:ScreenControl.MainContent>
    <controls:ScreenControl.UserInteractions>
        <Button>Do something</Button>
    </controls:ScreenControl.UserInteractions>
</controls:InstallerScreenControl>

相應的控件模板看起來略有簡化,如下所示:

<Style TargetType="{x:Type controls:ScreenControl}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type controls:ScreenControl}">
                <DockPanel Width="530">
                    <DockPanel DockPanel.Dock="Top">
                        <!-- Some static content -->
                        <ContentPresenter Content="{Binding MainContent, RelativeSource={...}}"
                                          DataContext="{Binding DataContext, RelativeSource={...}}"/>
                    </DockPanel>
                    <DockPanel DockPanel.Dock="Bottom" Background="LightGray" Height="50">
                        <StackPanel DockPanel.Dock="Right" Orientation="Horizontal" HorizontalAlignment="Right">
                            <ContentPresenter Content="{Binding UserInteractions, RelativeSource={...}}" 
                                              DataContext="{Binding DataContext, RelativeSource={...}}" />
                        </StackPanel>
                    </DockPanel>
                </DockPanel>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

現在,我想在UserInteractions區域中允許幾個元素。 但是, ContentPresenter僅允許單個元素。 通過閱讀,似乎我需要使用ItemsPresenter ,但這僅在我繼承自ItemsControl嗎?

我嘗試將UserInteractions依賴項屬性的類型設置為ObservableCollection<UIElement> (我發現的大多數文章都將其設置為object ,這就是我所擁有的),並且這種方法在沒有編譯錯誤的情況下可以正常工作。子級,但在渲染時僅顯示(Collection) ,而不顯示實際按鈕。

我想念什么?

假設UserInteractions是UI元素的集合,則應立即使用:

<ItemsControl ItemsSource="{Binding UserInteractions, RelativeSource={...}}"/>

如果UserInteraction對象是純數據對象,則還必須定義ItemTemplate

<ItemsControl ItemsSource="{Binding UserInteractions, RelativeSource={...}}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            ...
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

暫無
暫無

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

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