SelectionChanged(ListBox)时框架为空?

Frame is Null when SelectionChanged (ListBox)?

我正在使用 ListBox 作为 "Navigation" 栏。当用户选择一个项目(例如:选项)时,我会更改框架的来源。但是,我需要选择第一项才能使其看起来像该页面处于活动状态。

我将其添加到我的 ListBoxItem 样式中: <Setter Property="SelectedIndex" Value="0"></Setter>

唯一的问题是,我收到一个空异常错误:

如何在定义PageContainer (Frame) 后"select" ListBox 中的Item?我是 WPF 的新手,但我仍然不明白为什么在触发 selectedIndex 事件之前未定义框架。

澄清一下,PageNavigation 是列表框,PageContainer 是框架。

旁注

我应该:

  1. 甚至将 ListBox 用于多页软件之类的东西(即: CCleaner)

  2. 正在使用框架和页面。 (我见过另一种使用 Custom 的方法 用户控件,但我认为这有点奇怪)

XAML

<Style x:Key="PageNavigation" TargetType="{x:Type ListBox}">
    <!--<Setter Property="SelectedIndex" Value="1"></Setter>-->
    <Setter Property="Background" Value="#eee"></Setter>
    <Setter Property="BorderThickness" Value="0"></Setter>
    <Setter Property="Margin" Value="0"></Setter>
    <Setter Property="FontSize" Value="18"></Setter>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="ListBox">
                <Border Name="Border" BorderThickness="0, 0, 1, 0" BorderBrush="Gray" Background="#eee">
                    <ScrollViewer Focusable="false">
                        <StackPanel IsItemsHost="True"></StackPanel>
                    </ScrollViewer>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

主内 Window:

        <ListBox Name="PageNavigation" Style="{StaticResource PageNavigation}" ItemContainerStyle="{StaticResource PageNavigationItem}" SelectionChanged="PageNavigation_SelectionChanged">
            <ListBoxItem Tag="Home.xaml">Home</ListBoxItem>
            <ListBoxItem Tag="TestPage.xaml">Test Page</ListBoxItem>
            <ListBoxItem Tag="OptionsPage.xaml">Options</ListBoxItem>
        </ListBox>

前几天我刚好读到 "Initialized vs. Loaded" 文章,我认为它可能适用于这个问题。

我认为正在发生的是持有 PageContainerPageNavigation 的控件正在开始初始化。您从本文中了解到,所有子元素都将在父 Initialized 事件被触发之前完成初始化。

文章还指出:

The Initialized event typically fires when the properties of an element have all been set.

话虽如此,我认为您的 PageNavigation 甚至在您的 PageContainer 存在之前就已被初始化,因此当 SelectionChanged 被触发并且您尝试访问控件时——你得到了 NRE。

此外,我过去遇到过问题,其中 SelectionChanged 会在应用程序启动期间、初始化期间触发;然后当我指定 SelectedItem/Index 时。我怀疑这也可能是你的问题。

归根结底,空测试将阻止 NRE,然后只有当 PageContainer 存在时才会设置源——这也是一种常见的做法。

if(this.PageContainer != null)
{
    this.PageContainer.Source = new Uri(navigationPath, UriKind.Relative);
}