扩展的WPF工具包PropertyGrid数字格式

时间:2012-11-15 14:56:21

标签: wpf xaml propertygrid

我正在使用Extended WPF Toolkit中的PropertyGird。我能够做几乎我需要的任何事情,但我无法格式化数字。

我有一个double属性,我希望它只显示两位小数(字符串格式应为"F2")。我试过放[DisplayFormat(DataFormatString = "{F2}")]属性,但它似乎没有任何影响(我仍然有我的10位数字)。

我做错了吗?我确实需要为double类型创建一个CustomEditor,它会格式化所有我的double属性吗?

感谢任何帮助!

编辑:使用网格的AutoGenerateProperties选项自动绑定属性。我没有明确的约束力。如果可能的话,我想保持这种方式,但这不是强制性的。

2 个答案:

答案 0 :(得分:1)

我终于找到了一种在PropertyGrid.EditorDefinitions中使用DataTemplate的方法。在下面的示例中,Double类型的每个属性都会得到一个" DoubleUpDown"编辑器的格式为" 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>

通过在EditorTemplateDefinition.TargetProperties中命名特定属性,以下只有这些属性会受到DataTemplate的影响。

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

答案 1 :(得分:0)

我只能找到一种方法(非常脏):

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);
    }
}
相关问题