采用ThreadPoolTimer C#uwp的时钟程序

时间:2016-05-03 02:31:27

标签: c# xaml win-universal-app

这是对前一个问题How to display a clock with the current time in a Windows Core IoT app?的回答建模的,我得到一个异常:“应用程序调用了一个为不同线程编组的接口。”如果我使用click事件更改属性,绑定将起作用。

<TextBlock Margin="15" Name="timec" Text="{x:Bind Path=RunClock.Clock, Mode=OneWay}"></TextBlock>

和Xaml:

 public class test : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged = delegate { };
    ThreadPoolTimer _clockTimer = null;
    private string str1 = "";
    public string Str1
    {
        set
        {
            str1 = value;
            this.OnPropertyChanged();
        }
        get { return str1; }
    }
    public test()
    {

        _clockTimer = ThreadPoolTimer.CreatePeriodicTimer(_clockTimer_Tick, TimeSpan.FromMilliseconds(1000));
                }
    async private void _clockTimer_Tick(ThreadPoolTimer timer)
    {
       await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,() =>
        {
            DateTime dt = DateTime.Now;
            Str1 = dt.ToString();
        });
    }
    public void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

提前谢谢!

更新,工作代码:

                <TextBlock Margin="15" Name="timec" Text="{x:Bind test1.Str1, Mode=OneWay}"></TextBlock>

Xaml(test1是viewmodel的一个实例):

awk '{print $1}' * | sort | uniq -c | sort -nrk1,1 | head -n
-- where n = number of top IDs you want to view

1 个答案:

答案 0 :(得分:0)

异常是因为您尝试修改不同线程中的UI

使用此

 private void _clockTimer_Tick(ThreadPoolTimer timer)
    {
       var dispatcher = Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher;
       await dispatcher.RunAsync(
        CoreDispatcherPriority.Normal, () =>
        {
        // Your UI update code goes here!
        DateTime datetime = DateTime.Now;
        Str1 = datetime.ToString();
        });
    }