我已经实现了一个附加属性,当它的值发生变化时,它会改变媒体元素的位置。
附属物的定义如下:
public class MediaElementHelper
{
public static void SetBindablePosition(UIElement element, TimeSpan value)
{
if (element == null)
{
throw new ArgumentNullException();
}
element.SetValue(BindablePositionProperty, value);
}
public static TimeSpan GetBindablePosition(UIElement element)
{
if (element == null)
{
throw new ArgumentNullException();
}
return (TimeSpan) element.GetValue(BindablePositionProperty);
}
private static void PostionPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
var richEditControl = obj as MediaElement;
if (richEditControl != null)
{
richEditControl.Position = (TimeSpan) e.NewValue;
}
}
public static readonly DependencyProperty BindablePositionProperty =
DependencyProperty.RegisterAttached("BindablePosition",
typeof (TimeSpan), typeof (MediaElementHelper),
new FrameworkPropertyMetadata(new TimeSpan(), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
PostionPropertyChanged));
}
}
并在MainWindow中:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_OnClick(object sender, RoutedEventArgs e)
{
var newFileDialog = new OpenFileDialog();
newFileDialog.ShowDialog();
MediaElement.Source = new Uri(newFileDialog.FileName);
}
private void MediaElement_OnMediaOpened(object sender, RoutedEventArgs e)
{
Slider.Maximum = MediaElement.NaturalDuration.TimeSpan.TotalMilliseconds;
Slider.SmallChange = 1;
Slider.LargeChange = 5000;
}
}
和xaml:
<MediaElement Name="MediaElement"
Grid.Row="0"
loc:MediaElementHelper.BindablePosition="{Binding ElementName=Slider, Path=Value, Converter={StaticResource DoubleToTimeSpanConverter}}"
MediaOpened="MediaElement_OnMediaOpened" />
我的转换器类定义如下:
public class DoubleToTimeSpanConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return TimeSpan.FromMilliseconds((double) value);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return System.Convert.ToDouble(((TimeSpan) value).Milliseconds);
}
}
但是,当我拖动滑块的拇指时效果很好,但是当我什么都不做的时候,滑块的拇指不会自动移动。我该怎么做才能使这种绑定成为拖曳方式结合?
答案 0 :(得分:0)
没有完美的方法 - 我过去解决它的方法是创建一个新的DispatcherTimer
对象,它会轮询Position
元素,并更新滑块。
// this is the timer
timerVideoTime = new DispatcherTimer();
timerVideoTime.Interval = TimeSpan.FromSeconds(1);
timerVideoTime.Tick += new EventHandler(timer_Tick);
timerVideoTime.Start();
}
// the actual timer handler.
void timer_Tick(object sender, EventArgs e)
{
// Check if the movie finished calculate it's total time
if (MyMediaElement.NaturalDuration.TimeSpan.TotalSeconds > 0)
{
if (TotalTime.TotalSeconds > 0)
{
var sliderValue = MyMediaElement.Position.TotalSeconds /
TotalTime.TotalSeconds;
if(Slider.Value != sliderValue){
Slider.SetCurrentValue(Slider.ValueProperty, sliderValue);
}
}
}