0
我有一個視圖。在這個視圖裏面,我使用了我的自定義控件GrMenu。Wpf DataTemplate引用自身; DataContext(= null)問題
<pages:PageBase>
<Grid>
<views:GrMenu x:Name="InsightsMenu" Menu="{Binding Insights}" SelectItemCommand="{Binding LoadInsightCommand}" SelectedMenuItem="{Binding SelectedInsight, Mode=TwoWay}"/>
</Grid>
</pages:PageBase>
GrMenu基本上就像樹視圖,但使用ItemsControls實現。
<UserControl x:Name="GrMenuUserControl" x:Class="Views.GrMenu">
<UserControl.Resources>
<telerik:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
<telerik:InvertedBooleanToVisibilityConverter x:Key="InvertedBooleanToVisibilityConverter"/>
<converters:BoolToColourConverter x:Key="BoolToColourConverter" />
<DataTemplate x:Key="MenuItemTemplate" DataType="{x:Type groupingMenu:IMenuItem}">
<Grid>
<telerik:RadExpander HorizontalAlignment="Left" VerticalAlignment="Top" Visibility="{Binding HasChildren, Converter={StaticResource BooleanToVisibilityConverter}, Mode=OneWay}">
<telerik:RadExpander.Header>
<Label Content="{Binding Header}" />
</telerik:RadExpander.Header>
<TextBlock>
<InlineUIContainer>
<ItemsControl ItemsSource="{Binding Children}" ItemTemplate="{DynamicResource MenuItemTemplate}" Margin="20,0,0,0"/>
</InlineUIContainer>
</TextBlock>
</telerik:RadExpander>
<Button
Visibility="{Binding HasChildren, Converter={StaticResource InvertedBooleanToVisibilityConverter}, Mode=OneWay}"
Content="{Binding Header}"
MinWidth="200"
HorizontalAlignment="Stretch"
HorizontalContentAlignment="Left"
Margin="20,2,2,2"
BorderThickness="0"
Click="MenuItemButton_OnClick"
Tag="{Binding Id}"
Command="{Binding SelectItemCommand, ElementName=GrMenuUserControl}"
CommandParameter="{Binding .}"
Background="{Binding IsSelected, Converter={StaticResource BoolToColourConverter}}"
/>
</Grid>
</DataTemplate>
</UserControl.Resources>
<Grid x:Name="LayoutRoot" DataContext="{Binding ElementName=GrMenuUserControl}">
<ItemsControl x:Name="GroupedMenuItems" ItemsSource="{Binding Menu.GroupedMenuItems}" ItemTemplate="{DynamicResource MenuItemTemplate}"/>
</Grid>
</UserControl>
而且我的網頁基地(其中異常射擊類)看起來像這樣:
public abstract class PageBase : Page
{
protected PageBase()
{
Unloaded += Page_Unloaded;
}
public void Page_Unloaded(object sender, RoutedEventArgs e)
{
if(DataContext!=null)
DataContext = null;
}
}
而且這裏的東西。當我瀏覽到我的屏幕,然後離開我調用它試圖null分配到DataContext但沒有說的Page_Unloaded方法:
Unable to cast object of type 'System.Windows.Controls.ControlTemplate' to type 'System.Windows.DataTemplate'.
我已經想通了,這個問題涉及到這一行:
<InlineUIContainer>
<ItemsControl ItemsSource="{Binding Children}" ItemTemplate="{DynamicResource MenuItemTemplate}" Margin="20,0,0,0"/>
</InlineUIContainer>
好像我只拿出的ItemTemplate屬性一切工作正常,但後來我失去了數據模板遞歸特權。
你們知道我可以使用任何解決方法嗎?