2012-12-08 59 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