XAML不正确或没有完全反映逻辑。
您在开头指定了数据上下文分配片段
DataContext = new ProgressViewModel(projectInfo);
,但在XAML中,您可以从参考资料中获取源代码。这两种方式有点矛盾。
我还怀疑您没有完全正确地设置将TimeSpan转换为字符串的格式。
看看我的实现示例。它基于以下课程:
An example of my implementation of base classes (.Net 8): BaseInpc, RelayCommand, RelayCommandAsync, RelayCommand, RelayCommandAsync.
using Simplified;
namespace SOTopics2025.SO.Barta.question79330621
{
public class Stopwatch : BaseInpc
{
public TimeSpan ElapsedTime { get; private set; }
public DateTime StartTime { get; private set; }
public bool IsEnabled { get; private set; }
private readonly Timer timer;
public Stopwatch()
{
timer = new Timer(OnTick);
StartCommand = new RelayCommand
(
() =>
{
if (IsEnabled)
return;
StartTime = DateTime.Now;
IsEnabled = true;
ElapsedTime = TimeSpan.Zero;
RaisePropertyChanged(string.Empty);
StartCommand!.RaiseCanExecuteChanged();
StopCommand!.RaiseCanExecuteChanged();
timer.Change(10, 10);
},
() => !IsEnabled
);
StopCommand = new RelayCommand
(
() =>
{
if (IsEnabled)
{
IsEnabled = false;
RaisePropertyChanged(string.Empty);
StartCommand.RaiseCanExecuteChanged();
StopCommand!.RaiseCanExecuteChanged();
timer.Change(Timeout.Infinite, Timeout.Infinite);
}
},
() => IsEnabled
);
}
private void OnTick(object? state)
{
ElapsedTime = DateTime.Now - StartTime;
RaisePropertyChanged(nameof(ElapsedTime));
}
public RelayCommand StartCommand { get; }
public RelayCommand StopCommand { get; }
}
}
<Window x:Class="SOTopics2025.SO.Barta.question79330621.StopwatchTestWindow"
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:SOTopics2025.SO.Barta.question79330621"
mc:Ignorable="d"
Title="StopwatchTestWindow" Height="250" Width="400">
<Window.DataContext>
<local:Stopwatch/>
</Window.DataContext>
<UniformGrid Columns="2">
<TextBlock Text="{Binding StartTime}" VerticalAlignment="Center" HorizontalAlignment="Center">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Setter Property="Foreground" Value="Red"/>
<Style.Triggers>
<DataTrigger Binding="{Binding IsEnabled}" Value="True">
<Setter Property="Foreground" Value="Green"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
<TextBlock Text="{Binding ElapsedTime, StringFormat=hh\\:mm\\:ss\\.ff}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<Button Content="Start" Padding="15 5" VerticalAlignment="Center" HorizontalAlignment="Center" Command="{Binding StartCommand, Mode=OneWay}"/>
<Button Content="Stop" Padding="15 5" VerticalAlignment="Center" HorizontalAlignment="Center" Command="{Binding StopCommand, Mode=OneWay}"/>
</UniformGrid>
</Window>