2012-12-08 61 views
1

我想尝试一下能够有一个转换器,其参数可以与当前数据上下文绑定。任何人都可以告诉我为什么到达Convert()函数时,Source属性始终为空?从DependencyObject继承的自定义IValueConverter

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> 

回答

2

一个可行的办法是让你的转换器将来自可冻结代替(Hillberg Freezable trick)继承。然后,你甚至可以在你的资源中定义你的转换器,并在你的绑定中引用它作为一个属性,而不是一个额外的子元素。

+0

谢谢,这似乎工作,但我不知道为什么。为什么原始代码不起作用?我觉得我缺少在你链接的解决方法之前需要的知识是有意义的。 – hammer

+0

基本上,由于某种原因,Freezable继承了DataContext,而大部分资源和不属于可视树的部分都没有。他们很特别。这里..这解释更多http://drwpf.com/blog/2008/05/22/leveraging-freezables-to-provide-an-inheritance-context-for-bindings/ – Alan