使用IOC时绑定未更新

时间:2016-09-14 13:28:17

标签: c# data-binding mvvm-light uwp-xaml template10

我从来没有在我的任何应用程序中使用 IOC ,今天我决定学习如何使用它,但我遇到了一些绑定问题。

当页面显示时,绑定值会立即更新,但稍后更改其中的某些值不会反映到页面。

以下是导致问题的部分片段:

服务

public class TimerService : BindableBase, ITimerService
{
    public TimerService()
    {   
        RemainingTime = UpdateInterval;
        var updateTimer = new DispatcherTimer
        {
            Interval = TimeSpan.FromSeconds(1)
        };            
        updateTimer.Tick += UpdateTimerOnTick;
        updateTimer.Start();
    }        

    private double _remainingTime;

    public int UpdateInterval { get; set; } = 90;

    public double RemainingTime
    {
        get { return _remainingTime; }
        set { 
            // From Template10, it calls RaisePropertyChanged (and even calling it manually doesn't help)
            Set(ref _remainingTime, value); 
        }
    }

    private void UpdateTimerOnTick(object sender, object o)
    {
        RemainingTime -= 1;
        if (Math.Abs(RemainingTime) < 0.05) RemainingTime = UpdateInterval;
        // Timer is running fine as I can see the prints
        Debug.WriteLine($"{RemainingTime}");            
    }
}

定位器

public class ViewModelLocator
{
    static ViewModelLocator()
    {
        ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);

        if (ViewModelBase.IsInDesignModeStatic)
        {
            SimpleIoc.Default.Register<ITimerService, DesignTimeTimerService>();
        }
        else
        {
            SimpleIoc.Default.Register<ITimerService, TimerService>(true);
        }

        SimpleIoc.Default.Register<MainPageViewModel>();
    }

    public MainPageViewModel MainPageViewModel => ServiceLocator.Current.GetInstance<MainPageViewModel>();
}

视图模型

public class MainPageViewModel : ViewModelBase
{

    public ITimerService TimerService { get; }

    public MainPageViewModel(ITimerService timerService)
    {
        TimerService = timerService;
    }

}

<Page x:Class="Views.MainPage"
      ...
      DataContext="{Binding Source={StaticResource ViewModelLocator}, Path=MainPageViewModel}"
      mc:Ignorable="d">

      ...

      <ProgressBar Maximum="{x:Bind ViewModel.TimerService.UpdateInterval}"
                   ...
                   Value="{x:Bind ViewModel.TimerService.RemainingTime, Mode=OneWay, Converter={StaticResource EmptyConverter}}" />


      ...

      (.cs file)

      private MainPageViewModel ViewModel => DataContext as MainPageViewModel;

我期望的是,随着计时器的进行,ProgressBar的值会减少,但它会保持在我设置的第一个值上。

我还尝试添加一个空的转换器来查看是否发生了某些事情但是ProgressBar从未收到更新事件。

你对此有任何暗示吗?

0 个答案:

没有答案