WP开发笔记-一些Converter

一些Converter,包括:bool到visibility的转换;string到visibility的转换等;

说明:使用单例模式。同时包含了反向转换。即:为false时显示,为true时隐藏。

默认效果是: true=>visible, false=>collapsed

public class BooleanToVisibilityConverter : IValueConverter
{
    protected static BooleanConverter converter = new BooleanConverter();

    public virtual object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return converter.ConvertBoolean(value);
    }

    protected object InvertConvertBoolean(object value)
    {
        return converter.ConvertBoolean(value, true);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    protected class BooleanConverter
    {
        public object ConvertBoolean(object value, bool invert = false)
        {
            if (value == null)
                return Visibility.Collapsed;
            bool result = (bool)value;
            result = invert ? !result : result;
            return result ? Visibility.Visible : Visibility.Collapsed;
        }

        public object ConvertString(object value, bool invert = false)
        {
            if (value == null)
                return Visibility.Collapsed;
            string s = value as string;
            if (string.IsNullOrEmpty(s) || s.Trim() == "0")
                return Visibility.Collapsed;
            else
                return Visibility.Visible;
        }

        public object ConvertObject(object value, bool invert = false)
        {
            if (value == null)
                return Visibility.Collapsed;
            return Visibility.Visible;
        }

        public object ConvertFill(object value)
        {
            if (value == null)
                return (Brush)Application.Current.Resources["PhoneForegroundBrush"];
            return (bool)value ?
            (Brush)Application.Current.Resources["PhoneAccentBrush"]
            : (Brush)Application.Current.Resources["PhoneForegroundBrush"];
        }
    }
}
反向转换:

public class InvertBooleanToVisibilityConverter : BooleanToVisibilityConverter
    {
        public override object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return base.InvertConvertBoolean(value);
        }
    }
string的转换:

public class StringToVisibilityConverter : BooleanToVisibilityConverter
    {
        public override object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return converter.ConvertString(value);
        }
    }
示例代码: GitHub>>

你可能感兴趣的:(windows,wp,phone,Chicken)