我正在学习WPF MVVM,我遇到了一个问题。我每隔200ms计算一个类中的变量值,然后我将它发送到触发PropertyChanged事件的ViewModel,但该值没有出现在View上。当我将此代码复制到ViewModel构造函数的计算变量值时,一切正常。你能给我一些提示我做错了吗?
我计算值的类:
public class CalculatingSecondsTask
{
public string seconds { get; set; }
public CalculatingSecondsTask()
{
Task.Run(async () =>
{
int i = 0;
while (true)
{
await Task.Delay(200);
seconds = (i++).ToString();
UpdateSecondsInViewModel(seconds);
}
});
}
public void UpdateSecondsInViewModel(string secs)
{
ViewModel test = new ViewModel();
test.Seconds_To_Start = secs;
}
我的ViewModel:
public class ViewModel : INotifyPropertyChanged
{
private string mSeconds_To_Start;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (propertyName == null)
throw new ArgumentNullException("propertyExpression");
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
public string Seconds_To_Start
{
get
{
return mSeconds_To_Start;
}
set
{
mSeconds_To_Start = value;
OnPropertyChanged(nameof(Seconds_To_Start));
}
}
我的观点就像:
<Window x:Class="Program.Views.StartWindow"
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:Program.Views"
xmlns:ViewModel="clr-namespace:Program.ViewModels"
mc:Ignorable="d"
Title="Program" Height="110" Width="400">
<Window.DataContext>
<ViewModel:ViewModel/>
</Window.DataContext>
<Grid>
<!-- Text -->
<TextBlock x:Name="Seconds_To_Start" HorizontalAlignment="Center">
<Run Text="{Binding Seconds_To_Start}" />
<Run Text="seconds" />
</TextBlock>
</Grid>
</Window>