开发者

Infinite Loop when binding slider in MVVM

开发者 https://www.devze.com 2023-01-18 07:19 出处:网络
I have a video progress slider in XAML thus: <Slider Minimum=\"0\" Value=\"{Binding Position,Mode=OneWay}\" Maximum=\"{Binding Duration}\" IsMoveToPointEnabled=\"True\"/>

I have a video progress slider in XAML thus:

<Slider Minimum="0" Value="{Binding Position,Mode=OneWay}" Maximum="{Binding Duration}" IsMoveToPointEnabled="True"/>

And code in my viewmodel to update Position on Clock.CurrentTimeInvalidated(), which keeps the slider tracking current progress:

private void Play()
{
Uri next = _carousel.Dequeue();
_timeline = new MediaTimeline(next);
_timeline.RepeatBehavior = RepeatBehavior.Forever;
_clock = _timeline.CreateClock();
MyMediaElement.Clock = _clock;
_clock.CurrentTimeInvalidated += new EventHandler(UpdatePosition);
_clock.Controller.Begin();
}

public void UpdatePosition(object sender, EventArgs e)
{
  Position = MyMediaElement.Position.TotalMilliseconds;
}

This works fine, except when I implement ValueChanged to set Clock.Controller.Seek():

private void seekSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
DisplayViewModel vm = (DisplayViewModel)this.DataContext;
TimeSpan ts = new TimeSpan(0, 0, 0, 0, (int)seekSlider.Value);
vm.MyMediaElement.Clock.Controller.Seek(ts, TimeSeekOrigin.BeginTime);
}

(In my user control's codebehind until I figure out event-to-command routing)

At this point I get an infinite loop. Previously in non-MVVM I simply disabled the Slider.ValueChanged() event handler during UpdatePosition:

public void UpdatePosition(object sender, EventArgs e)
{
  seekSlider.ValueChanged -= new EventHandler(seekSlider_ValueChanged);
  Position = MyMediaElement.Position.TotalMilliseco开发者_C百科nds;
  seekSlider.ValueChanged += new EventHandler(seekSlider_ValueChanged);
}

...but now I'm in a viewmodel I no longer have access to my slider control.

Is there another way to disable the infinite loop/event handler?


Consider moving the logic from seekSlider_ValueChanged to the setter of the Position property in your ViewModel.

0

精彩评论

暂无评论...
验证码 换一张
取 消