在以下 XAML 中,我尝试将各种 DataTemplates 直接绑定到 Grid ContentPresenter。我将 Button 放在 Grid 中只是为了向自己证明 ContentTemplate 已绑定并且 DataTriggers 工作正常 - 它们是(注意我此时不需要任何类型的控件)。如果我用<Button
>替换<ContentPresenter
> 什么都不会出现。显然,我在这里遗漏了一些非常简单的东西。
<DataTemplate x:Key="MyTemplate">
<Grid Style="{StaticResource GridAllocatedStyle}">
<Ellipse Stroke="#FF5A71FB"
StrokeThickness="0.5"
Style="{StaticResource EllipseFinanciallyAllocatedStyle}" />
<TextBlock Style="{StaticResource TextBlockInsideEllipseStyle}"
Text="A"
ToolTip="Allocated" />
</Grid>
</DataTemplate>
<DataTemplate x:Key="AllocationTemplate">
<Grid>
<Button> <!-- I want to bind to the Grid.ContentPresenter here -->
<Button.Style>
<Style TargetType="Button">
<Style.Triggers>
<DataTrigger Binding="{Binding Allocated}" Value="PreAllocatedBoth">
<Setter Property="ContentTemplate" Value="{StaticResource MyTemplate}" />
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
</Grid>
</DataTemplate>
为了完整起见,这就是我想要实现的目标:
<DataTemplate x:Key="AllocationTemplate">
<Grid>
<Grid.Style>
<Style TargetType="Grid">
<Style.Triggers>
<DataTrigger Binding="{Binding Allocated}" Value="None">
<Setter Property="Visibility" Value="Collapsed" />
</DataTrigger>
</Style.Triggers>
</Style>
</Grid.Style>
<ContentPresenter> <!-- I want to bind to the Grid.ContentPresenter here -->
<ContentPresenter.Style>
<Style TargetType="ContentPresenter">
<Style.Triggers>
<DataTrigger Binding="{Binding Allocated}" Value="FinanciallyAllocated">
<Setter Property="ContentTemplate" Value="{StaticResource MyTemplate}" />
</DataTrigger>
</Style.Triggers>
</Style>
</ContentPresenter.Style>
</ContentPresenter>
</Grid>
</DataTemplate>