我可以在ContentTemplate中的单个Content或ContentSource中指向两个ContentPresenter吗?

Jav*_*ier 2 wpf contentpresenter

我已经创建了一个类似于Outlook 2007的NavigationPane。在Outlook中,当窗格被折叠并且单击侧栏时,它用来弹出Selected NavigationItem内容。我在ControlTemplete中使用contentpresenter模仿了相同的行为(一个用于TabControl的SelectItemHost,另一个用于Popup)。但是问题是当打开弹出窗口时,NavigationPane会在不显示内容的情况下选择内容,而当我们从另一个导航项切换回相同的导航项时会显示该内容。我正在使用TabControl和TabItem作为NavigationPane和NavigationPaneItem。

我将“ SelectedContent”指向两个ContentPresenter的ContentSource

Jos*_*h G 5

您可以ContentPresenter在控件模板中定义两个对象,并根据需要将它们都指向相同的内容源:

<ControlTemplate x:Key="WeirdButton" TargetType="Button">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <Border Grid.RowSpan="2" Background="{TemplateBinding Background}" />
        <ContentPresenter ContentSource="Content"/>
        <ContentPresenter ContentSource="Content" Grid.Row="1"/>
    </Grid>
</ControlTemplate>
Run Code Online (Sandbox Code Playgroud)

但是,这有一些非常不寻常的副作用。因为您不能将同一视觉对象放入视觉树中的两个位置,所以仅当按钮的子内容不是视觉对象(或从Visual派生)时,此模板才能按预期工作。如果内容是其他类型的数据,并且视觉效果是由数据模板生成的,则一切正常。将按钮的内容设置为字符串(<Button Content="OK"/>)也可以。

请注意,使用可视笔刷可以达到相同的效果:

<ControlTemplate x:Key="WeirdButton" TargetType="Button">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <Border Grid.RowSpan="2" Background="{TemplateBinding Background}" />
        <ContentPresenter x:Name="presenter" ContentSource="Content"/>
        <Rectangle Grid.Row="1" 
                   Width="{Binding ActualWidth, ElementName=presenter}" Height="{Binding ActualHeight, ElementName=presenter}">
            <Rectangle.Fill>
                <VisualBrush Visual="{Binding ElementName=presenter}" Stretch="None" AlignmentX="Left"/>
            </Rectangle.Fill>
        </Rectangle>
    </Grid>
</ControlTemplate>
Run Code Online (Sandbox Code Playgroud)

这种方法的缺点是您无法与可视笔刷中的控件进行交互。因此,如果您希望重复项上的按钮,文本框和其他控件也具有交互性,则必须采用更接近第一个模板的方法。