Reputation: 2275
So i have a Media Element and a Slider and i want to bind the Position property of MediaElement to the slider in ViewModel
Like:-
<Slider
x:Name="PositionSlider"
Minimum="0"
Maximum="{Binding Position,Mode=TwoWay"/>
<MediaElement
x:Name="mediaElement"
Position="{Binding Position,Mode=TwoWay"/>
but i cannot bind position of the media element since it's not a dependency property
.
is there any alternative to achieve this?
Upvotes: 1
Views: 1047
Reputation: 7591
you can implement an attached property that is boundable, that changes the position of the media element when its value is changed.
The Attached Property is defined as follows:
public class MediaElementExtension
{
public static TimeSpan GetBindablePosition(DependencyObject obj)
{
return (TimeSpan)obj.GetValue(BindablePositionProperty);
}
public static void SetBindablePosition(DependencyObject obj, double value)
{
obj.SetValue(BindablePositionProperty, value);
}
// Using a DependencyProperty as the backing store for BindablePosition. This enables animation, styling, binding, etc...
public static readonly DependencyProperty BindablePositionProperty =
DependencyProperty.RegisterAttached("BindablePosition", typeof(TimeSpan), typeof(MediaElementExtension), new PropertyMetadata(new TimeSpan(), BindablePositionChangedCallback));
private static void BindablePositionChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
MediaElement mediaElement = d as MediaElement;
if (mediaElement == null) return;
mediaElement.Position = (TimeSpan)e.NewValue;
}
}
And now you can use it as follows:
<MediaElement local:MediaElementExtension.BindablePosition="{Binding SomePropertyFromViewModel}" />
Upvotes: 2