Cynical
Cynical

Reputation: 9558

Extended WPF Toolkit PropertyGrid Number format

I'm using the PropertyGird from Extended WPF Toolkit. I was able to do almost anything I needed, but I am unable to format numbers.

I have a double property, and I want to have it shown with just two decimal digits (the string format for that should be "F2"). I have tried by putting the [DisplayFormat(DataFormatString = "{F2}")] attribute, but it doesn't seem to have any effect (I still have my 10-digits number).

Am I doing something wrong? Do I really need to create a CustomEditor for the double type, which would format all my double properties like that?

Any help is appreciated!

EDIT: The property is automatically bound using the AutoGenerateProperties option of the grid. I don't have an explicit binding. If it is possible I would like to keep it this way, but it's not mandatory.

Upvotes: 2

Views: 1924

Answers (2)

chrigu
chrigu

Reputation: 21

I finally found a way using a DataTemplate in the PropertyGrid.EditorDefinitions. In the example below, every property of type Double gets a "DoubleUpDown" editor with a format of "F2".

xmlns:System="clr-namespace:System;assembly=mscorlib"
xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"

<xctk:PropertyGrid ...>
    <xctk:PropertyGrid.EditorDefinitions>
        <xctk:EditorTemplateDefinition>

            <xctk:EditorTemplateDefinition.TargetProperties>
                <xctk:TargetPropertyType Type="{x:Type System:Double}" />
            </xctk:EditorTemplateDefinition.TargetProperties>

            <xctk:EditorTemplateDefinition.EditingTemplate> 
                <DataTemplate>
                    <xctk:DoubleUpDown FormatString="F2" 
                                       Value="{Binding Value, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
                </DataTemplate>
            </xctk:EditorTemplateDefinition.EditingTemplate>

        </xctk:EditorTemplateDefinition>
    </xctk:PropertyGrid.EditorDefinitions> 
</xctk:PropertyGrid>

By naming specific properties in EditorTemplateDefinition.TargetProperties, only these properties will be affected by the DataTemplate following.

<xctk:EditorTemplateDefinition.TargetProperties>
    <System:String>Volume</System:String>
    <System:String>Weight</System:String>
</xctk:EditorTemplateDefinition.TargetProperties>

Upvotes: 2

skink
skink

Reputation: 5711

I could find only one way of doing that (very dirty):

void PropertyGrid_SelectedObjectChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
    foreach (var p in pg.Properties)
    {
        if (p.PropertyType == typeof(double)) // or filter by p.Name
            p.Value = string.Format("{0:F2}", p.Value);
    }
}

Upvotes: 1

Related Questions