How to display percent-values using ContentStringF

2020-06-28 16:06发布

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" Value="{}{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

2条回答
家丑人穷心不美
2楼-- · 2020-06-28 16:41

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 %
查看更多
混吃等死
3楼-- · 2020-06-28 16:44

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

查看更多
登录 后发表回答