我做了一些你正在寻找的常规操作IValueConverter
:
public class BooleanConverter<T> : DependencyObject, IValueConverter {
public static DependencyProperty FalseProperty =
DependencyProperty.Register( "False", typeof( T ), typeof( BooleanConverter<T> ), new PropertyMetadata( default( T ) ) );
public static DependencyProperty TrueProperty =
DependencyProperty.Register( "True", typeof( T ), typeof( BooleanConverter<T> ), new PropertyMetadata( default( T ) ) );
public T False {
get { return (T) GetValue( FalseProperty ); }
set { SetValue( FalseProperty, value ); }
}
public T True {
get { return (T) GetValue( TrueProperty ); }
set { SetValue( TrueProperty, value ); }
}
public BooleanConverter( T trueValue, T falseValue ) {
True = trueValue;
False = falseValue;
}
public object Convert( object value, Type targetType, object parameter, CultureInfo culture ) {
bool b = false;
if ( value is bool ) b = (bool) value;
else if ( value is string ) b = bool.Parse( value as string );
return b ? True : False;
}
public object ConvertBack( object value, Type targetType, object parameter, CultureInfo culture ) {
return value is T && EqualityComparer<T>.Default.Equals( (T) value, True );
}
}
然后我实现了许多继承自泛型类型的新类。例如:
[ValueConversion( typeof( bool ), typeof( Brush ) )]
public class BooleanToBrushConverter : BooleanConverter<Brush> {
public BooleanToBrushConverter() :
base( new SolidColorBrush( Colors.Black ), new SolidColorBrush( Colors.Red ) ) { }
}
IMultiValueConverter
您可能可以为课程做类似的事情。True
&属性仍然存在,False
只是决定返回哪个属性值的逻辑涉及对传递的数组中的值进行逻辑与或或运算。
像这样的东西:
public class AndConverter<T> : DependencyObject, : DependencyObject, IMultiValueConverter{
public static DependencyProperty FalseProperty =
DependencyProperty.Register( "False", typeof( T ), typeof( AndConverter<T> ), new PropertyMetadata( default( T ) ) );
public static DependencyProperty TrueProperty =
DependencyProperty.Register( "True", typeof( T ), typeof( AndConverter<T> ), new PropertyMetadata( default( T ) ) );
public T False {
get { return (T) GetValue( FalseProperty ); }
set { SetValue( FalseProperty, value ); }
}
public T True {
get { return (T) GetValue( TrueProperty ); }
set { SetValue( TrueProperty, value ); }
}
public AndConverter( T trueValue, T falseValue ) {
True = trueValue;
False = falseValue;
}
public object Convert( object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture ) {
return (<Your logic to compute the result goes here>) ? True : False;
}
public object[] ConvertBack( object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture ) {
// . . .
}
}
然后你可以创建你的类来转换为可见性:
[ValueConversion( typeof( bool ), typeof( Visibility ) )]
public class AndVisibilityConverter : AndConverter<Visibility> {
public AndVisibilityConverter() :
base( Visibility.Visible, Visibility.Hidden ) { }
}