1
我如下已經實現附加屬性當其值改變時改變所述媒體元素的位置..綁定的MediaElement和滑塊值
附加屬性被定義:
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));
}
}
並在主窗口:
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);
}
}
,當我拖着滑塊的拇指它工作得很好,但是當我做什麼,滑塊的拇指不會自動移動。什麼我應該怎麼做這個綁定作爲拖曳方式綁定?