从 DependencyObject 继承的自定义 IValueConverter



我想尝试能够拥有一个参数可以与当前数据上下文绑定的转换器。谁能告诉我为什么在访问 Convert() 函数时,Source 属性总是为空?

namespace WpfApplication32
{
    public class ConverterTest : DependencyObject, IValueConverter
    {
        public static readonly DependencyProperty SourceProperty =
            DependencyProperty.Register("Source", typeof(DependencyObject), typeof(ConverterTest));
        public DependencyObject Source
        {
            get { return (DependencyObject)this.GetValue(SourceProperty); }
            set { this.SetValue(SourceProperty, value); }
        }
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value;
        }
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value;
        }
    }
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            Value = 7;
            InitializeComponent();
            DataContext = this;
        }
        public float Value
        {
            get;
            set;
        }
    }
}


<Window x:Class="WpfApplication32.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication32">
    <Slider>
        <Slider.Value>
            <Binding Path="Value">
                <Binding.Converter>
                    <local:ConverterTest Source="{Binding}"/>
                </Binding.Converter>
            </Binding>
        </Slider.Value>
    </Slider>
</Window>

一种可能的解决方案是让你的转换器继承自 Freezable (Hillberg Freezable 技巧)。然后,您甚至可以在资源中定义转换器,并在绑定中将其作为属性而不是额外的子元素引用。

相关内容

  • 没有找到相关文章

最新更新