Winforms ComboBox ICustomFormatter

时间:2014-09-03 17:57:45

标签: c# winforms combobox

我一直在尝试使用ICustomFormatter ComboBox的{​​{1}}属性。如果我使用FormatInfo,我可以让格式化程序正确执行。我也可以使用String.Format(...)正确执行它,但前提是我使用自定义对象填充ComboBox。我真正希望ComboBox使用我的格式化程序来填充ComboBox的每个类型。如果我使用双精度填充ComboBox,则ComboBox的{​​{1}}方法的formatType参数为GetFormat(...)而不是IFormatProvider

有没有办法允许我的格式化程序用于填充NumberFormatInfo任何类型?

示例代码

ICustomFormatter

所以,我感兴趣的是这里的ComboBox

public class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        comboBox1.Items.AddRange(new object[] { 0, new A(1), new B(2), new C(3) });

        var formatter = new CustomFormatter();

        comboBox1.FormatInfo = formatter;
        comboBox1.FormatString = "0";

        // This prints 4ft in the Output window
        Console.WriteLine(String.Format(formatter, "{0}", 4));

        // The comboBox's drop down will show the following:
        // 0 <= **This is the one I'm interested in. can I force usage of my CustomFormatter for int/float/double/etc.**
        // CustomFormatterTest.A
        // 2
        // 3ft
    }
}

public class CustomFormatter : IFormatProvider, ICustomFormatter
{
    public object GetFormat(Type formatType)
    {
        // A breakpoint placed here will get hit 4 times
        // 1: formatType is NumberFormatInfo
        // 2. formatType is ICustomFormatter
        // 2.5. this object's Format method gets called
        // 3. formatType is ICustomFormatter
        // 3.5. this object's Format method gets called
        if (formatType == typeof(ICustomFormatter))
            return this;

        return null;
    }

    // 2.5. arg is 3
    // 3.5. arg is 4
    public string Format(string format, object arg, IFormatProvider formatProvider)
    {
        return String.Format("{0}ft", (int)arg);
    }
}

public class A
{
    private int _i;

    public A(int i)
    {
        _i = i;
    }
}

public class B
{
    private int _i;

    public B(int i)
    {
        _i = i;
    }

    public override string ToString()
    {
        return _i.ToString();
    }
}

public class C : IFormattable
{
    private int _i;

    public E(int i)
    {
        _i = i;
    }

    public string ToString(string format, IFormatProvider formatProvider)
    {
        var formatter = formatProvider.GetFormat(typeof(ICustFormatter)) as ICustomFormatter;

        if (formatter != null)
        {
            return formatter.Format(format, _i, formatProvider);
        }

        return String.Empty;
    }
}

有没有办法将自定义格式化程序提供的格式应用于0而不将其包装在单独的对象中?

0 个答案:

没有答案