我有它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}" />
但是,从模板,我想给它“OuterGrid”的内容和位置,通过设置Grid.Row
等附加属性:
<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
的DataTemplate
效果。
有几乎可用的解决方案(例如https://social.msdn.microsoft.com/Forums/vstudio/en-US/cc9ed724-600e-415a-b775-bae09eea66f8/cant-use-attached-properties-inside-a-datatemplate?forum=wpf),但他们总是适用的ItemsControl
- 我没有一个ItemsControl
,我想定位为整个DataTemplate
工作。
该ContentTemplate
不能设置Grid.Row
和Grid.Column
的ContentControl
的附加属性。该模板仅适用于Content
的ContentControl
。
但是你可以在你的ContentTemplateSelector
编程这样的:
public class SBATemplateSelector : DataTemplateSelector
{
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
if (item != null)
{
ContentPresenter cp = container as ContentPresenter;
if (cp != null)
{
ContentControl cc = VisualTreeHelper.GetParent(cp) as ContentControl;
if (cc != null)
{
Grid.SetRow(cc, 4);
Grid.SetColumn(cc, 0);
Grid.SetRowSpan(cc, 5);
Grid.SetColumnSpan(cc, 10);
}
}
}
...
}
}