在WPF窗口的构造函数中,应该在InitializeComponent()之前应该去什么? [英] In a constructor for a WPF Window, what should go before InitializeComponent() and what after?

查看:914
本文介绍了在WPF窗口的构造函数中,应该在InitializeComponent()之前应该去什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一般来说,在 InitializeComponent()之前,我已经初始化了 Window 控制包含在后面。但是,我没有一直一致,我没有真正注意到一个问题的排序。所以:

In general, I've been initializing the properties of the Window itself before InitializeComponent() and setting up controls contained within afterwards. However, I haven't been all that consistent, and I haven't really noticed a problem with the ordering. So:


  • 我可能会做一些可怕的事情吗?特别是,在 InitializeComponent()之前设置子控件的属性有什么问题吗?

  • 这方面的好习惯是什么?

  • Am I (potentially) doing something horrible? In particular, are there any issues with setting properties of child controls before InitializeComponent()?
  • What is good style in this regard?

编辑:有一些有点矛盾,让我更具体:

Since the first two answers I got were a little bit contradictory, let me be more specific:

public Foo Foo {get; protected set}
public FooWindow (Foo foo)
{
    Foo = foo;
    this.Closing += FooWindow_Closing;
    Foo.Frobbed += Foo_Frobbed;

    InitializeComponent();

    this.DataContext = this;
    this.Title = Foo.Name() + " Window";

    FooListView.ItemSource = Foo.CalculateList();

    FocusManager.SetFocusedElement(this, FooListView);
}

这是正确的吗?我应该在我的 Window 构造函数中没有任何东西。

Is this about right? Should I just be doing MVVM and not have anything in my Window constructor?

推荐答案

通过在一些其他代码之后调用InitializeComponents,您可能无意中使用在XAML中设置的内容覆盖属性,或使用未初始化的对象。通常代码隐藏比XAML更高的优先级,所以我会离开InitializeComponents(aka,解析和加载XAML)在顶部。

By calling InitializeComponents after some other code you run the risk of accidentally overwriting properties with things that were set in the XAML or of using an uninitialized object. Usually the code-behind is a higher priority than the XAML so I would leave InitializeComponents (aka, parse and load the XAML) at the top.

这篇关于在WPF窗口的构造函数中,应该在InitializeComponent()之前应该去什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆