如何将ContentTemplate直接绑定到网格?
问题描述:
在下面的XAML中,我试图将各种DataTemplates直接绑定到Grid ContentPresenter。为了向我自己证明ContentTemplate是绑定的并且DataTriggers工作正常 - 它们是(注意我不想在此处进行任何类型的控制),我将Button放在了Grid中。 如果我用<ContentPresenter
替换<Button
>没有任何显示。 显然我在这里错过了一些非常简单的事情。如何将ContentTemplate直接绑定到网格?
<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>
答
也许什么也不显示了,因为你没有任何内容的contentPresenter
设置?
页面:看起来你有很多与你的问题无关的代码(椭圆样式,很多模板)。需要一段时间才能完成所有这些代码,所以我会要求删除不需要的代码。
我想要做的是设置DataTemplate(MyTemplate)作为内容演示者的内容 - 但显然我需要提供一个可以接受ContentTemplate的控件。考虑到我想显示MyTemplate的内容,我会在这里使用哪种控件? – 2011-02-23 20:23:24
@Jeremy,这个用法看起来是正确的。 'ContentPresenter'应该接受'DataTemplate'。 ContentPresenter唯一的选择是ContentControl,但是我怀疑这个改变会对你有所帮助。 – Snowbear 2011-02-23 20:32:41
不幸的是,这正是问题 - DataTemplate没有显示出来。我会去看看ContentControl,看看它是否有所作为。无论如何,我重构了整个事物,以便它不再使用DataTemplate - 但它现在看起来非常混乱:)如果我像第一个示例中那样绑定到Button,我会得到正确的绑定,所以我知道DataTrigger正在工作,但如上所述,我只是想让DataTemplate的内容出现在网格中。 – 2011-02-24 20:56:37