views:

389

answers:

2

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

A: 

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

serge_gubenko
Hi Serge,I went away from my original code and built a more simple example where I created some DataGridTextColumns by hand in XAML. One was bound to a number column of a DataTable. In this setup, Your hint worked quite well and I finally got my desired formatted value of "18.0%".Now I still need to find out how to alter the automatic binding when the DataGrid' AutoGenerateColumns is set to "True" again... but that's a new post if I fail :-)Best regardsJoerg
Joerg Reinhardt
A: 

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 %
Andrew Jackson
Hi Andrew,thanks for Your answer. Actually You are quite correct when one deals with pure strings, but Your hint didn't help me in this case. At least it did not when I tried to set the DataType attribute of the DataTable or the DataColumn. The resulting formatted value kept reading "0.18".Best regardsJoerg
Joerg Reinhardt