2013-02-11 20 views
0

我想我的問題主題有點混亂。總之,我想要的:WPF:轉換器「捕獲」的基類轉換方法

我在我的應用程序中有很多Converters。他們中的許多人不實施ConvertBack方法。所以我想有一個BaseConverter類,它提供了一個簡單的空實現ConvertBack和所有其他轉換器從BaseConverter繼承。

我的BaseConverter的想法:

public class BaseConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     // do nothing in this dummy implementation 
     return null; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     // do nothing in this dummy implementation 
     return null; 
    } 
} 

我的瘋狂轉換器之一:

public class CrazyConverter : BaseConverter 
{ 
    public new object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     return ACrazyConverionOfTheValue(...); 
    } 
} 

不過,如果我嘗試這樣,用我CrazyConverter,我總是在最後Convert方法BaseClass。我的新Convert方法永遠不會被調用。我究竟做錯了什麼?

感謝您的回覆!

+0

所以你的XAML?你能證明嗎? – 2013-02-11 18:36:22

+0

就像這樣:'' – 2013-02-11 18:43:39

回答

3

您需要製作基類virtual中的方法,而您的子類應該使用override(而不是new)。

public class BaseConverter : IValueConverter 
{ 
    public virtual object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     // do nothing in this dummy implementation 
     return null; 
    } 

    public virtual object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     // do nothing in this dummy implementation 
     return null; 
    } 
} 

public class CrazyConverter : BaseConverter 
{ 
    public override object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     return ACrazyConverionOfTheValue(...); 
    } 
} 

編輯:您也可能要考慮重構這需要通過使類和Convert抽象的,就像讓Convert覆蓋:你是如何真正使用它在

public abstract class BaseConverter : IValueConverter 
{ 
    public abstract object Convert(object value, Type targetType, object parameter, CultureInfo culture); 

    public virtual object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     // do nothing in this dummy implementation 
     return null; 
    } 
} 
+0

謝謝!這對我來說非常合適,我將使用抽象類方法。 – 2013-02-11 18:44:44