我通过以下方式定义了DataTemplate:
<s:SurfaceWindow.Resources>
<ImageBrush x:Key="WindowBackground" Stretch="None" Opacity="0.6" ImageSource="pack://application:,,,/Resources/WindowBackground.jpg"/>
<DataTemplate x:Key="ContainerItemTemplate">
<Grid>
<Border BorderThickness="1" BorderBrush="White" Margin="3">
<s:SurfaceTextBox IsReadOnly="True" Width="120" Text="{Binding Path=name}" Padding="3"/>
</Border>
<s:SurfaceButton Content="Expand" Click="SourceFilePressed"></s:SurfaceButton>
</Grid>
</DataTemplate>
</s:SurfaceWindow.Resources>
然后我用它将ItemTemplate添加到LibraryContainer:
<Grid Name="RootGrid" Background="{StaticResource WindowBackground}" >
<s:ScatterView Name="RootScatter">
<Viewbox>
<s:LibraryContainer Name="RootContainer" Grid.Row="0" ViewingMode="Bar">
<s:LibraryContainer.BarView>
<s:BarView Rows="2" NormalizedTransitionSize="2.5,0.8" ItemTemplate="{StaticResource ContainerItemTemplate}">
</s:BarView>
</s:LibraryContainer.BarView>
<s:LibraryContainer.StackView>
<s:StackView NormalizedTransitionSize="1,1" ItemTemplate="{StaticResource ContainerItemTemplate}">
</s:StackView>
</s:LibraryContainer.StackView>
</s:LibraryContainer>
</Viewbox>
</s:ScatterView>
</Grid>
稍后,我向ScatterView添加了一个新的ScatterViewItem:
ScatterViewItem item = new ScatterViewItem();
FrameworkElement element = surfaceWindow as FrameworkElement;
DataTemplate tmpl = element.FindResource("ContainerItemTemplate") as DataTemplate;
LibraryContainer container = new LibraryContainer();
container.ViewingMode = LibraryContainerViewingMode.Bar;
container.ItemsSource = itms;
container.BarView.ItemTemplate = tmpl;
item.Content = container;
surfaceWindow.getRootScatter().Items.Add(item);
不幸的是,我总是在行中得到NullReferenceException:
container.BarView.ItemTemplate = tmpl;
其他信息:
对象surfaceWindow在此方法中传递。它是对我已定义DataTemplate的文件的引用。
答案 0 :(得分:2)
除非您的LibraryContainer对象的构造函数构建LibraryContainer.BarView对象,否则此时它将为null。
修改强> 好的,所以忽略以前的尝试......我现在已经对表面控件做了一些阅读。
回到您通过密钥获取数据模板的原始方法:
DataTemplate tmpl = element.FindResource("ContainerItemTemplate")
如果你在那里设置了一个断点,那么是返回了模板还是此时为空?