I can't figure out how to add the format parameter to the following DataGrid column. I need to show the number with two decimal points.

I have a silverlight DataGrid that I'm adding columns to dynamically. I create the column and apply a dynamic binding (which I know works)

    public static DataGridTextColumn CreateFloatColumn(int index, string fieldName, string header, string description)
    {
        DataGridTextColumn column = new DataGridTextColumn();
        column.Header = header;
        column.HeaderStyle = BuildColumnHeaderStyle(description);
        Binding newBinding = new Binding("floatValuesList[" + index + "]");
        column.Binding = newBinding;
        column.CellStyle = BuildCellStyle(fieldName, description);
        return column;
    }

Now I also need to format the value. In this case it is a float value being shown. How do I apply formatting to the binding? At this point all I want is the number and two decimal points to show, but I'd like it to be a little flexible and let me show a variable number of decimal points.

(Edit: Removed string IValueConverter concept to keep the question cleaner)

有帮助吗?

解决方案

I hate to answer my own question, and I think I was misleading in how I added a potential solution using a value converter to my original question - so sorry about that. The solution turned out to be simple. You pass the format string along with the binding.

        column.Binding.StringFormat = "0.00";

Here is the full solution

    public static DataGridTextColumn CreateFloatColumn(int index, string fieldName, string header, string description)
    {
        DataGridTextColumn column = new DataGridTextColumn();
        column.Header = header;
        column.HeaderStyle = BuildColumnHeaderStyle(description);
        column.Binding = new Binding("floatValuesList[" + index + "]");
        column.Binding.StringFormat = "0.00";
        column.CellStyle = BuildFloatCellStyle(fieldName, description);
        return column;
    }

其他提示

You should be able to do: newBinding.ConverterParameter = "formatString";

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top