我在代码背后实现了一个基本的数据绑定,这是代码:

Binding bindingSlider = new Binding();
bindingSlider.Source = mediaElement.Position;
bindingSlider.Mode = BindingMode.TwoWay;
bindingSlider.Converter = (IValueConverter)Application.Current.Resources["DoubleTimeSpan"];
slider.SetBinding(Slider.ValueProperty, bindingSlider);

这是转换器的代码,
class DoubleTimeSpan : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter,
string language)
    {
        return ((TimeSpan)value).TotalSeconds;
    }

    public object ConvertBack(object value, Type targetType, object parameter,
string language)
    {
        return TimeSpan.FromSeconds((double)value);
    }
}

即使我没有收到编译器的错误消息,但是绑定代码不起作用。为什么?

最佳答案

bindingSlider.Source = mediaElement.Position ; // boo!

这是错误的。Source是包含要绑定到的属性的对象。你想要的是
bindingSlider.Source = mediaElement ;
bindingSlider.Path   = new PropertyPath ("Position") ;

07-28 07:05