[英]How can I control the loading sequence of controls?
我的英语水平很差,因为我不是以英语为母语的人。
我的应用程序有一个 MainWindowView 和 MainWindowBehavior 也 MainWindowView 有控制(编辑器)如下代码。
<MainWindowView>
<Grid>
<TabControl>
<TabItem>
<Grid>
<Editor x:Name="editor"/>
</Grid>
</TabItem>
</TabControl>
</Grid>
<i:Interaction.Behaviors>
<behaviors:MainWindowBehavior/>
</i:Interaction.Behaviors>
</MainWindowView>
MainWindowBehavior 使用 MainWindowView 的 LoadedEventHandler 中 Editor 的属性。 以下代码显示了上述逻辑。
protected override void OnDetaching()
{
this.AssociatedObject.Loaded -= AssociatedObject_Loaded;
base.OnDetaching();
}
protected override void OnAttached()
{
base.OnAttached();
this.AssociatedObject.Loaded += AssociatedObject_Loaded;
}
private void AssociatedObject_Loaded(object sender, RoutedEventArgs e)
{
this.mainWindow = sender as MainWindow;
// run time error
this.mainWindow.editor.Parser.ParsingFailed += Parser_ParsingFailed;
}
但是编译器显示运行时错误,因为编辑器的 Parser 属性的值为 null。 我试图在构造器上初始化编辑器的解析器属性,OnApplyTemplate function,加载的事件处理程序,但 3 个案例都比 MainWindow 的加载事件处理程序调用晚。
结果,产生运行时错误。
我认为编辑器的Loaded EventHandler必须更早调用MainWindowBehavior的Loaded EventHandler。 但实际上,顺序相反。
我不知道为什么顺序相反。
如何按照我的想法更改加载顺序?
感谢您的阅读。
也许你不能改变事件的顺序,但你可以肯定改变你收听这些事件的方式。 我建议您连接到mainWindow
中的一个事件,该事件将在设置其editor
属性时指示您。
您的代码将变为:
private void AssociatedObject_Loaded(object sender, RoutedEventArgs e)
{
this.mainWindow = sender as MainWindow;
// Here we don't access mainWindow.editor anymore, we hook-up to an event instead
this.mainWindow.OnEditorPropertyChanged += MainWindow_EditorPropertyChanged;
}
private void MainWindow_EditorPropertyChanged(object sender){
{
var mainWindow = sender as MainWindow;
if (mainWindow.editor != null) {
mainWindow.editor.Parser.ParsingFailed += Parser_ParsingFailed;
}
}
在您的MainWindow
中,确保在设置其editor
属性时引发事件,例如:
public delegate void OnEditorPropertyChangedEventHandler(object sender);
public event OnEditorPropertyChangedEventHandler OnEditorPropertyChanged;
// Backing field
private Editor _editor;
public Editor editor {
get => _editor;
set => {
_editor = value;
OnEditorPropertyChanged?.Invoke(this); // Raise the event
}
}
在听从您的建议时,我找到了问题的原因。
我认为编辑器的 OnApplyTemplate function 比 MainWindowView 的 Loaded 事件更早被调用。 但是,实际上是没有调用Editor的OnApplyTemplate function。
我一直对我的问题理解错误。 对不起...现在我会解决我的问题。
编辑器是自定义控件。 我错过了在 Generic.xaml 文件中添加以下代码的代码。
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/WpfControls;component/Themes/Editor.xaml"/>
</ResourceDictionary.MergedDictionaries>
现在我在 Generic.xaml 和 OnApplyTemplate function 中添加了上面的代码,通常调用它也比 MainWindowView 的 Loaded 事件更早调用。
感谢您对我的问题的帮助和关注。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.