如何分配全局初始化事件?

时间:2018-07-25 13:40:13

标签: c# wpf

我的App.xaml.cs中有以下代码:

protected override void OnStartup(StartupEventArgs e)
{
    EventManager.RegisterClassHandler(typeof(TextBox), TextBox.TextChangedEvent, new RoutedEventHandler(TextBox_TextChangedEvent));
}
private void TextBox_TextChangedEvent(object sender, RoutedEventArgs e)
{
    // Works
}

我想对InitializedEvent做类似的事情。
这是我失败的尝试:

protected override void OnStartup(StartupEventArgs e)
{
    EventManager.RegisterClassHandler(typeof(FrameworkElement), FrameworkElement.InitializedEvent, new EventHandler(FrameworkElement_InitializedEvent));
}
private void FrameworkElement_InitializedEvent(object sender, EventArgs e)
{

}

InitializedEvent是否在其他地方?
这有可能吗?

我尝试使用LoadedEvent:

protected override void OnStartup(StartupEventArgs e)
{
    EventManager.RegisterClassHandler(typeof(FrameworkElement), FrameworkElement.LoadedEvent, new RoutedEventHandler(FrameworkElement_LoadedEvent));
}
private void FrameworkElement_LoadedEvent(object sender, RoutedEventArgs e)
{
    // Fires only for Windows
}

仅针对Windows触发,而不针对Windows内部的控件触发。我确实意识到了;当我将加载的事件添加到窗口中具有的Label时;即使我的正常加载事件(我专门为Label创建的事件)为空,也会为该Label触发全局FrameworkElement_LoadedEvent。我也尝试过这些:

EventManager.RegisterClassHandler(typeof(Button), Button.LoadedEvent, new RoutedEventHandler(Button_LoadedEvent));
EventManager.RegisterClassHandler(typeof(Grid), Grid.LoadedEvent, new RoutedEventHandler(Grid_LoadedEvent));
EventManager.RegisterClassHandler(typeof(DataGrid), DataGrid.LoadedEvent, new RoutedEventHandler(DataGrid_LoadedEvent));

但是除非我在这些控件上添加另一个空的加载事件,否则它们不会触发。

我的目标是为每个已初始化的控件建立一个时间日志。

如何在不将加载的事件添加到我拥有的每个控件的情况下实现此目标?

(我有很多)

1 个答案:

答案 0 :(得分:6)

您在这里!

public partial class App : Application
{
    // ##############################################################################################################################
    // Constructor
    // ##############################################################################################################################

    #region Constructor

    static App()
    {
        // set MyInitialized=true for new windows (happens before Loaded)
        EventManager.RegisterClassHandler(typeof(Window), FrameworkElement.SizeChangedEvent, new RoutedEventHandler(OnSizeChanged));

        // our loaded handler
        EventManager.RegisterClassHandler(typeof(UIElement), FrameworkElement.LoadedEvent, new RoutedEventHandler(OnLoaded), true);
        EventManager.RegisterClassHandler(typeof(ContentElement), FrameworkContentElement.LoadedEvent, new RoutedEventHandler(OnLoaded), true);
    }

    private static void OnSizeChanged(object sender, RoutedEventArgs e)
    {
        //Console.WriteLine("SizeChanged {0}", sender);
        SetMyInitialized((Window) sender, true);
    }

    private static void OnLoaded(object sender, RoutedEventArgs e)
    {
        Trace.WriteLine($"{DateTime.Now:O}: {sender} loaded");
    }

    #endregion

    // ##############################################################################################################################
    // MyInitialized
    // ##############################################################################################################################

    #region MyInitialized

    public static void SetMyInitialized(UIElement element, bool value)
    {
        element.SetValue(MyInitializedProperty, value);
    }

    public static bool GetMyInitialized(UIElement element)
    {
        return (bool) element.GetValue(MyInitializedProperty);
    }

    public static readonly DependencyProperty MyInitializedProperty = DependencyProperty.RegisterAttached("MyInitialized", typeof (bool), typeof (App), new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.Inherits, OnMyInitializedChanged));

    private static void OnMyInitializedChanged(DependencyObject dpo, DependencyPropertyChangedEventArgs ev)
    {
        if ((bool)ev.NewValue)
        {
            // registering instance handler unbreaks class handlers
            if (dpo is FrameworkElement element)
                element.Loaded += _EmptyRoutedEventHandler;
            if (dpo is FrameworkContentElement contentElement)
                contentElement.Loaded += _EmptyRoutedEventHandler;
        } else
        {
            throw new ArgumentException("Cannot set to false", ev.Property.Name);
        }
        //Console.WriteLine("MyInitialized {0} {1}=>{2}", dpo, ev.OldValue, ev.NewValue);
    }

    private static readonly RoutedEventHandler _EmptyRoutedEventHandler = delegate { };

    #endregion              
}

XAML

<Window x:Class="WpfApp3.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:WpfApp3"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800"
        d:DataContext="{d:DesignInstance local:MainWindow}">
        <Grid>
            <Border Background="Green" VerticalAlignment="Center" HorizontalAlignment="Center" Width="30" Height="20">
                <TextBlock Background="Orange" Text="hello"></TextBlock>
            </Border>
        </Grid>
</Window>

示例Console的输出:

2018-07-31T14:20:52.6052225+02:00: WpfApp3.MainWindow loaded
2018-07-31T14:20:52.6112064+02:00: System.Windows.Controls.Border loaded
2018-07-31T14:20:52.6132008+02:00: System.Windows.Documents.AdornerDecorator loaded
2018-07-31T14:20:52.6141984+02:00: System.Windows.Controls.ContentPresenter loaded
2018-07-31T14:20:52.6141984+02:00: System.Windows.Controls.Grid loaded
2018-07-31T14:20:52.6151966+02:00: System.Windows.Controls.Border loaded
2018-07-31T14:20:52.6161935+02:00: System.Windows.Controls.TextBlock loaded
2018-07-31T14:20:52.6161935+02:00: System.Windows.Documents.AdornerLayer loaded