WPF: update / update management when loading windows

I want to show the time in a shortcut. The contents of the shortcut must be updated automatically when the window loads.

I have a simple WPF window with a Label control. As shown here

<Window x:Class="shoes.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300" Loaded="Window_Loaded">
    <Grid>
        <Label Margin="12" Name="lblSeconds"></Label>
        <Button Margin="68,22,135,0" Name="button1" Height="24" VerticalAlignment="Top" Click="button1_Click">Button</Button>
    </Grid>
</Window>

I looked at the code available here: http://geekswithblogs.net/NewThingsILearned/archive/2008/08/25/refresh--update-wpf-controls.aspx

And I changed like this:

public partial class Window1 : Window
{
    private static Action EmptyDelegate = delegate() { };

    public Window1()
    {
        InitializeComponent();

    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        if (IsLoaded)
        {
            LoopingMethod();
        }
    }

    private void LoopingMethod()
    {
        while(true)
        {
            lblSeconds.Content = DateTime.Now.ToLongTimeString();
            lblSeconds.Refresh();
            Thread.Sleep(10);
        }
    }
}
public static class ExtensionMethods
{

    private static Action EmptyDelegate = delegate() { };


    public static void Refresh(this UIElement uiElement)
    {
        uiElement.Dispatcher.Invoke(DispatcherPriority.Render, EmptyDelegate);
    }
}

I found that the code works very well when it fires through the button_Click event. I tried to get the code to fire the Window_Loaded event like this, but in vain. The contents of the window are never displayed.

What can I do to update the shortcut automatically when the window loads?

+3
source share
3

, OnLoad . , .

: Backgroundworker, .

, INotifyPropertyChanged, (), , PropertyChanged, ( ). (, Backgroundworker). .

Timer, , .

+3

, INotifyPropertyChanged CurrentTime DispatcherTimer, PropertyChanged ( "CurrentTime" ).

CurrentTime.

DispatcherTimer , .

+3

Instead of using an infinite loop, use DispatcherTimer

+1
source

Source: https://habr.com/ru/post/1705542/


All Articles