C# 初始化组件后未初始化UWP绑定
调用InitializeComponent后,数据绑定不会加载到UWP中。正因为如此,我的应用程序在尝试操作东西时出错,这些东西通常是绑定到的,但导航绑定没有加载。在OnNavigated事件中操作绑定属性的正确方法是什么C# 初始化组件后未初始化UWP绑定,c#,uwp,uwp-xaml,C#,Uwp,Uwp Xaml,调用InitializeComponent后,数据绑定不会加载到UWP中。正因为如此,我的应用程序在尝试操作东西时出错,这些东西通常是绑定到的,但导航绑定没有加载。在OnNavigated事件中操作绑定属性的正确方法是什么 <Page x:Class="StackApp.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.c
<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>
您是否从输出中得到错误? 您的数据类位于哪里? 是否设置了Datacontext 例如,如果您的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>
public sealed partial class MainPage : Page
{
String Test { get; set; } = "John";
public MainPage()
{
this.InitializeComponent();
DataContext = Test;
}
}
绑定尚未在导航到的
中解析。从:
与以前的XAML平台不同,OnNavigated方法是在加载可视化树之前调用的。这有以下影响:
- 您无法通过覆盖
OnNavigated
访问有效的父属性值。如果需要访问Parent
属性,请在加载的事件处理程序中执行此操作
- 不能使用
OnNavigatedTo
对目标页面上的控件进行元素操作或状态更改。相反,在新加载的页面内容的根目录下附加一个Loaded
事件处理程序,并在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;
}
}
这个问题可以通过调用Bindings.Initialize()来解决代码>在构造函数中,但我想知道根本原因是什么。请添加一些代码,如果没有它,将很难提供帮助,因为我们不知道issue@MartinZikmund添加示例problem@Shadow:是否等待组合框
加载完毕<代码>cb.Loaded+=(ss,ee)=>cb.SelectedIndex=0代码>@mm8,但我想知道正确的方法。我觉得你的建议是为了解决应用程序中糟糕的设计。我的问题与DataContext无关。我在问题中添加了示例代码;在InitializeComponent之前?实际上InitializeComponent在UI线程上执行,所以在调用代码隐藏线程之前调用OnNavigated,这就是为什么你的应用程序会崩溃。Hingi不知道确切原因,但问题仍然存在,调用构造函数,在UI线程上启动InitializeComponent,然后在构造函数结束后调用OnNavigated,然后在InitializeComponent完成后调用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;
}
}