这是基于对上一个问题的答案的模型的。如何在Windows Core IoT应用程序中显示带有当前时间的时钟?,我得到一个例外:“该应用程序调用了一个已编组用于另一个线程的接口。” 如果我通过click事件更改属性,则绑定有效。
public class RunClock: INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged = delegate { };
ThreadPoolTimer _clockTimer = null;
private string clock="";
public string Clock
{
set
{
clock= value;
this.OnPropertyChanged();
}
get { return clock; } }
public RunClock()
{
_clockTimer = ThreadPoolTimer.CreatePeriodicTimer(_clockTimer_Tick, TimeSpan.FromMilliseconds(1000));
private void _clockTimer_Tick(ThreadPoolTimer timer)
{
DateTime datetime = DateTime.Now;
Str1 = datetime.ToString();
}
public void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
和Xaml:
<TextBlock Margin="15" Name="timec" Text="{x:Bind Path=RunClock.Clock, Mode=OneWay}"></TextBlock>
先感谢您!
更新,工作代码:
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));
}
}
Xaml(test1是他的viewmodel的一个实例):
<TextBlock Margin="15" Name="timec" Text="{x:Bind test1.Str1, Mode=OneWay}"></TextBlock>
异常是因为您尝试在其他线程中修改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();
});
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句