通过DataTemplate在父ContentPresenter上设置附加属性

时间:2019-02-04 18:10:35

标签: wpf datatemplate attached-properties contentpresenter

我有一个Grid,其中有一个ContentControl

<Grid Name="OuterGrid">
    <!-- some controls on the grid -->

    <ContentControl Name="dbg1" Content="{Binding Mode=OneWay}" ContentTemplateSelector="{StaticResource SBATemplateSelector}"></ContentControl>

    <!-- some more controls on the grid -->
</Grid>

templateselector并不是很有趣:

<src:SBATemplateSelector x:Key="SBATemplateSelector"
    NormalTemplate="{StaticResource SBAreaTemplate1}"
    BigTemplate="{StaticResource SBAreaTemplate2}" />

但是我想从模板中通过设置Grid.Row等附加属性来提供内容并将其放置在“ OuterGrid”中:

<DataTemplate x:Key="SBAreaTemplate1" DataType="src:XCViewModel">
    <DataTemplate.Resources>
        <Style TargetType="ContentPresenter"> <!-- should go for only the 'parent' contentpresenter -->
            <Setter Property="Grid.Row" Value="4" />
            <Setter Property="Grid.Column" Value="0" />
            <Setter Property="Grid.RowSpan" Value="5" />
            <Setter Property="Grid.ColumnSpan" Value="10" />
        </Style>
    </DataTemplate.Resources>

    <Border Name="sbAreaBorder" BorderThickness="1" BorderBrush="Black">
        <ScrollViewer Name="sblbScroller" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
            <StackPanel Orientation="Vertical">
                <ItemsControl Name="notRelevantListBox" ItemsSource="{Binding}" ItemTemplateSelector="{StaticResource NotRelevantSelector}" />
            </StackPanel>
        </ScrollViewer>
    </Border>
</DataTemplate>

所以我什至不需要绑定,只是将属性设置为静态值。无论我做什么,我都无法使属性在ContentPresenter的{​​{1}}上生效。

几乎有可用的解决方案(例如https://social.msdn.microsoft.com/Forums/vstudio/en-US/cc9ed724-600e-415a-b775-bae09eea66f8/cant-use-attached-properties-inside-a-datatemplate?forum=wpf),但是它们总是应用DataTemplate-我没有ItemsControl,我希望整个{{ 1}}。

1 个答案:

答案 0 :(得分:1)

ContentTemplate无法设置Grid.Row的{​​{1}}和Grid.Column附加属性。模板仅应用于ContentControl中的Content

但是您可以通过编程方式在ContentControl中进行此操作:

ContentTemplateSelector