简体   繁体   中英

How can I tell when a visible change occurrs in a WPF Window?

I am capturing a visual representation of a WPF Window containing arbitrary content (controls, etc). I need to capture a picture of the Window each time the Window visually changes.

What can I do to tell when the Window has changed visually (size changed, content changed...anything the user can see with his eyes)? I don't care about any other changes.

I found some questions related to knowing when rendering is finished, but I'm not sure that's the exact same thing since I'm more concerned about the Window as a region, and I'm not concerned about the render happening if nothing visual changed.

You can use the Window.LayoutUpdated event, it should give you what you need.
Consider the following:

<Window x:Class="WpfApplication11.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525"
        LayoutUpdated="MainWindow_OnLayoutUpdated">
    <StackPanel>
        <Label>Last event:</Label>
        <TextBox x:Name="LastEvent"/>
        <Label x:Name="Updateable">Updateable</Label>
        <UniformGrid x:Name="Controls"/>
    </StackPanel>
</Window>

and the code behind:

public partial class MainWindow
{
    public MainWindow()
    {
        InitializeComponent();

        button_Click(null, null);

        var timer = new Timer(1000);
        timer.Elapsed += timer_Elapsed;
        timer.Start();
    }

    private void timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        Dispatcher.Invoke(new Action(() =>
            {
                var rand = new Random();

                Updateable.Background =
                    new SolidColorBrush(Color.FromRgb((byte) rand.Next(byte.MaxValue),
                                                      (byte) rand.Next(byte.MaxValue),
                                                      (byte) rand.Next(byte.MaxValue)));
            }));
    }

    private void button_Click(object sender, RoutedEventArgs e)
    {
        var button = new Button {Content = "Click Me!"};
        button.Click += button_Click;
        Controls.Children.Add(button);
    }

    private void MainWindow_OnLayoutUpdated(object sender, EventArgs eventArgs)
    {
        LastEvent.Text = DateTime.Now.ToLongTimeString();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM