调用InitializeComponent后,数据绑定未加载到UWP中。因此,我在尝试操作通常绑定到东西但未加载导航绑定的应用程序时遇到错误。在OnNavigated事件中操作绑定属性的正确方法是什么?
<Page
x:Class="StackApp.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="using:StackApp"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
mc:Ignorable="d">
<Grid>
<ComboBox x:Name="cb" ItemsSource="{x:Bind Data}" />
</Grid></Page>
public sealed partial class MainPage : Page
{
Data Data { get; set; } = Whatever;
public MainPage()
{
this.InitializeComponent();
//this.Bindings.Initialize();
//it can solve problem by manual binding loading
}
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
cb.SelectedIndex = 0; // Crash, because ComboBox has no items loaded yet
}
OnNavigatedTo
中的绑定尚未解析。从docs:
与以前的XAML平台不同,在加载可视树之前,将调用OnNavigated方法。这具有以下含义:
- 您无法通过覆盖
Parent
访问有效的OnNavigated
属性值。如果需要访问Parent
属性,请在Loaded
事件处理程序中访问。- 您不能将
OnNavigatedTo
用于目标页面上的元素操纵或控件的状态更改。而是在新加载的页面内容的根目录处附加Loaded
事件处理程序,并在Loaded
事件处理程序中执行任何元素操作,状态更改,事件连接等。
所以要等到加载ComboBox
之前,应该处理Loaded
事件:
public sealed partial class MainPage : Page
{
Data Data { get; set; } = Whatever;
public MainPage()
{
this.InitializeComponent();
this.Loaded += MainPage_Loaded;
}
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
cb.SelectedIndex = 0;
}
}
您是否从输出中得到错误?您的数据类位于哪里?是否已设置数据上下文?
例如,如果您的xaml看起来像这样:
<Page
x:Class="StackApp.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="using:StackApp"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
mc:Ignorable="d">
<Grid>
<Button Content="{Binding}" />
</Grid></Page>
然后在后面的代码中,应像这样设置DataContext:
public sealed partial class MainPage : Page
{
String Test { get; set; } = "John";
public MainPage()
{
this.InitializeComponent();
DataContext = Test;
}
}