2

我想尝试能够有一个转换器,其参数可以与当前数据上下文绑定。谁能告诉我为什么到达 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>
4

1 回答 1

3

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

于 2012-12-08T14:42:35.277 回答