开发者

How to display percent-values using ContentStringFormat?

Greetings to the enlightened ones!

I'm playing on this for several hours now, but wasn't successful (perhaps because I'm quite new to WPF):

I have a DataGrid whose DataContext is bound to a DataTable. The DataGrid is of fixed size and its purpose is to hold a value table y(x) (i.e. the headers show the x-values and the corresponding y-values are pasted from the clipboard and shown in the first DataGridRow). So far so good. The values are pasted (assigned as strings to dataTable.rows[0][i] where i=0...n) perfectly and displayed well.

But the numbers displayed are percent-values and I want them to be displayed as such:

"0.18" shall become "18 %"

So, I decided to cope with this using a style which is to be applied to all DataGridCell objects:

<Style TargetType="{x:Type Controls:DataGridCell}">
    <Style.Setters>
        <Setter Property="ContentStringFormat" Va开发者_高级运维lue="{}{0:P}"/>
        <Setter Property="Foreground" Value="DarkGray"/>
        <Setter Property="Background" Value="Yellow"/>
    </Style.Setters>
</Style>

Then the background and foreground colors are adopted fine, but the numbers are still displayed as decimals (i.e. "0.18" still reads "0.18".

How can I fix this?

Thanks in advance Joerg


I believe you can specify StringFormat along with binding definition for the datagrid column. Smth. like this:

<DataGridTextColumn Header="Column_Header" Binding="{Binding Path=Field_Name, StringFormat='{}{0:P}'}"/>

hope this helps, regards


I think the problem is that the datatype you are trying to format is not a number. Try changing the table data type to double or some other numeric type.

Here is an example to illustrate my point:

string stringValue = "0.18";
string formattedStringValue = String.Format("{0:P}", stringValue);
// formattedStringValue = 0.18

double doubleValue = 0.18;
string formattedDoubleValue = String.Format("{0:P}", doubleValue);
// formattedDoubleValue = 18.00 %
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜