WPF ContentRendered事件没有触发?

时间:2018-06-01 11:59:28

标签: c# wpf

我确定我忽视了一些简单的事情,但WPF并不是我通常会工作的东西,所以我对此略有不满。

我正在尝试为要在后台运行的应用程序显示“启动画面”。它基本上是Windows操作系统的进程包装器。

我有一个WPF Window定义如下:

public partial class MainWindow : Window
{
    private Timer _timer;

    public MainWindow()
    {
        InitializeComponent();
        ContentRendered += MainWindow_ContentRendered;
    }

    private void MainWindow_ContentRendered(object sender, EventArgs e)
    {
        _timer = new Timer(5000);
        _timer.Elapsed += TimerOnElapsed;
        _timer.Enabled = true;
        _timer.Start();
    }

    private void TimerOnElapsed(object sender, ElapsedEventArgs e)
    {
        Dispatcher.Invoke(() =>
        {
            Hide();
            Close();
        });

    }

    ~MainWindow()
    {
        _timer.Dispose();
    }
}

public partial class MainWindow : System.Windows.Window, System.Windows.Markup.IComponentConnector {

    private bool _contentLoaded;

    /// <summary>
    /// InitializeComponent
    /// </summary>
    [System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
    public void InitializeComponent() {
        if (_contentLoaded) {
            return;
        }
        _contentLoaded = true;
        System.Uri resourceLocater = new System.Uri("/MySolution.WindowsWrapper;component/mainwindow.xaml", System.UriKind.Relative);

        #line 1 "..\..\MainWindow.xaml"
        System.Windows.Application.LoadComponent(this, resourceLocater);

        #line default
        #line hidden
    }

    [System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
    [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
    [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
    [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
    [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
    void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) {
        this._contentLoaded = true;
    }
}

XAML看起来像:

<Window x:Class="MySolution.WindowsWrapper.MainWindow"
        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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:MySolution.WindowsWrapper"
        mc:Ignorable="d"
        Title="Splash" Height="100" Width="327" WindowStyle="None" 
        HorizontalAlignment="Center" VerticalAlignment="Center" 
        AllowsTransparency="True" WindowStartupLocation="CenterScreen" ShowInTaskbar="False" Topmost="True">
    <Window.Background>
        <ImageBrush ImageSource="my-logo-large.png"/>
    </Window.Background>
    <Grid VerticalAlignment="Center" HorizontalAlignment="Center">

    </Grid>
</Window>

...在我的Program.cs文件中,我有类似的东西:

    [STAThread]
    public static void Main(string[] args)
    {
        var splashScreen = new MainWindow();
        splashScreen.Show();

        SetupSystemTrayIcon();

        var showConsole = args.Any(x => x.ToLowerInvariant().Contains("showconsole"));
        StartService(showConsole);
        WaitToDie();
    }

启动画面按预期显示...但计时器从未初始化,永远不会触发,因此它永远不会消失。

根据我的阅读,当显示窗口时,应该触发ContentRendered事件......但这似乎不会发生。我做错了什么?

1 个答案:

答案 0 :(得分:2)

我建议您删除自定义Main方法,然后将代码移至App.xaml.cs类的OnStartup方法:

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);

        SetupSystemTrayIcon();

        var showConsole = args.Any(x => x.ToLowerInvariant().Contains("showconsole"));
        StartService(showConsole);
    }
}

确保StartupUri中的MainWindow.xaml媒体资源设为App.xaml

<Application x:Class="WpfApp2.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:WpfApp2"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
    </Application.Resources>
</Application>

然后你应该得到一个调度程序和一个被激活的窗口。