我有一個UWP項目以及一個WPF項目。兩個項目都需要相同的轉換器。但接口IValueConverter
是在另一個名稱空間中的WPF中的UWP,而且是最後一個參數不相同(在WPF中,它是在UWP中的CultureInfo它是一個字符串)。 那麼爲兩個項目創建轉換器的最佳做法是什麼?如果我想在WPF和UWP項目中使用IValueConverter,最佳做法是什麼
我的解決方案是我有一個netstandard項目,它有一個ValueConverterBase類,它定義WPF IValueConverter和UWP的IValueConverter中的每兩個方法。它還定義了一個sepcific轉換器能夠實現兩個抽象方法:
public abstract class ValueConverterBase
{
public object Convert(object value, Type targetType, object parameter, string language)
{
return this.OnConvert(value, targetType, parameter, language);
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
return this.OnConvertBack(value, targetType, parameter, language);
}
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return this.OnConvert(value, targetType, parameter, culture.TwoLetterISOLanguageName);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return this.OnConvertBack(value, targetType, parameter, culture.TwoLetterISOLanguageName);
}
public abstract object OnConvert(object value, Type targetType, object parameter, string language);
public abstract object OnConvertBack(object value, Type targetType, object parameter, string language);
}
現在我可以創建在netstandard項目,做邏輯的轉換器。爲了能夠在UWP使用該轉換器和WPF的每個項目都必須建立從轉換器和特定的IValueConverter派生的類:
public class WpfConverter : CommonConverter, IValueConverter
{
}
public class UwpConverter : CommonConverter, IValueConverter
{
}
這種解決方案我必須添加的每個轉換器三個新類的問題。每個開發人員都必須知道這個解決方法。 另一點是我無法在轉換器中使用WPF或UWP特定邏輯。有人有另一種解決方案嗎?
新的解決方案
我結合我從@Anton Tykhyy和@Heinzi答案第一個解決方案。 我創建一個共享的項目,該項目將包含我的轉換器,並添加有我ValueConverterBase:
public abstract class ValueConverterBase
#if UWP
: Windows.UI.Xaml.Data.IValueConverter
#endif
#if WPF
: System.Windows.Data.IValueConverter
#endif
{ ...
是的,就是這樣。我想補充一點,Visual Studio 2015+支持[共享項目](http://dailydotnettips.com/2015/07/28/using-shared-project-across-multiple-applications-in-visual-studio-2015/) ,即你不需要不同的項目配置。您只需將netstandard項目替換爲WPF和UWP項目引用的「共享項目」即可。 – Heinzi