【问题标题】:Custom IValueConverter inheriting from DependencyObject从 DependencyObject 继承的自定义 IValueConverter
【发布时间】:2012-12-08 14:10:33
【问题描述】:

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

【问题讨论】:

    标签: wpf binding ivalueconverter dependencyobject


    【解决方案1】:

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

    【讨论】:

    • 谢谢,这似乎有效,但我不知道为什么。为什么原始代码不起作用?我觉得我缺少在您链接到的解决方法有意义之前所需的知识。
    • 基本上,出于某种原因,Freezable 继承了 DataContext,而大多数资源和不属于可视化树的东西却没有。他们很特别。这里..这解释了更多drwpf.com/blog/2008/05/22/…
    • 这完全让我着迷,很痛苦
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-18
    • 2012-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多