StringFormat for DataGridTextColumn

I have spent an hour trying to do the simplest thing, which of course is never the case with WPF...
I am binding a property of type TimeSpan to a column in a grid.  Without any formatting it works, except I don't like the format.  I want a single digit for 10ths of seconds (e.g. "2:45:19.7").  I'm currently doing this:
<DataGridTextColumn Header="{res:Res Id=PERIOD,Default=Period::}"
Width="Auto"
IsReadOnly="True"
Binding="{Binding TimePeriod, StringFormat={}{0:hh:mm:ss.f}}" />
When I run this, the column is blank.  I tried using single quotes around the '{}{0:hh:mm:ss.f}'.  I tried escaping the ":" in the string, like this: {0:hh\:mm\:ss\.f}.  None work - I see a blank column.  Do I need the first
"{}"?  What's that do.  Where is any of this explained?
This is so ridiculous.  I want to do the simplest thing but WPF makes it so difficult.

Forget the fact there's a textblock involved in my markup ( I don't have a convenient datagrid to hand ).
It's just an example of how the stringformat works.
Substitute
StringFormat={}{0:hh\\:mm\\:ss\\:f}
for your
StringFormat={}{0:hh:mm:ss.f}
I just wrote an explanation  of timespan stringformat here:
http://social.technet.microsoft.com/wiki/contents/articles/30609.wpf-tips-stringformat-on-timespan.aspx
Hope that helps.
Recent Technet articles: Property List Editing;
Dynamic XAML

Similar Messages

  • [WPF] Format column text for showing percentage

    Hi,
    in one column of my DataGrid I show percentage values.
    From database, I get the number:
    - in view, I would concatenate the char "%"
    - in edit, the user add his value and when mouse leaves cell automatically is concatenated the char "%"
    How can I implement it?
    Thanks.

    Replace any DataGridTextColumn with a DataGridTemplateColumn and specify a StringFormat for the TextBlock in the CellTemplate only:
    <DataGrid.Columns>
    <!--<DataGridTextColumn Binding="{Binding Val, StringFormat=P}"/>-->
    <DataGridTemplateColumn>
    <DataGridTemplateColumn.CellTemplate>
    <DataTemplate>
    <TextBlock Text="{Binding Val, StringFormat='\{0\}%'}"/>
    </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
    <DataGridTemplateColumn.CellEditingTemplate>
    <DataTemplate>
    <TextBox Text="{Binding Val}"/>
    </DataTemplate>
    </DataGridTemplateColumn.CellEditingTemplate>
    </DataGridTemplateColumn>
    </DataGrid.Columns>
    Note that the "number" source property must be an int, double, decimal etc. for the StringFormat to get applied.
    Please remember to close your threads by marking helpful posts as answer and then start a new thread if you have a new question.

  • WPF Data gird double value in cell round up automatically

    Hi All,
      I have one datagrid where one of the columns contains double values. I placed limitations on length and decimal part. Decimal part is always comes with 2 digits. Now during editing the cell that holds double value in DataGrid , if I enter value of
    99.99 then it is becoming 100. At this moment the cell is still under edit mode.
     If the columns hold decimal type values then this automatic round up is not happening. But due to some constraints , at this moment we can't change the columns type from  double to decimal. So I just want to disable the auto round up with double
    values in DataGrid. I searched in MSDN forums but did not find any , tried adding StringFormat for columns. But it did not help.
    I tested by keeping the double value outside of the DataGrid ( in editbox ) , I don't see any automatic round up. So I suspect there could be something with DataGrid that is resulting automatic round up.
    Is there any way to disable this automatic round op on double values in DataGrid? I welcome your comment.
    Thanks,
    Brahmaji.

    Well, 99.99 as you mentioned in your original post is not the same value as 9999999999999999. You cannot store the value 9999999999999999 in a double field.
    You could change the type to decimal to be able to store values with a higher precision:
    public class Movie
    public string Title { get; set; }
    public int Year { get; set; }
    public string Director { get; set; }
    public bool Hit { get; set; }
    public decimal Price { get; set; }
    new Movie()
    Title = "The Lawnmower Man",
    Year = 1992,
    Director = "Brett Leonard",
    Hit = true,
    Price = 22.23M
    If you want to prevent the value of the source property from getting set when an invalid double value is entered you could implement your own ValidationRule:
    namespace SampleGrid
    class MyValidationRule : System.Windows.Controls.ValidationRule
    public override System.Windows.Controls.ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
    string s = value.ToString();
    double d;
    if(double.TryParse(s, out d))
    return new System.Windows.Controls.ValidationResult(false, "invalid value");
    return System.Windows.Controls.ValidationResult.ValidResult;
    <DataGridTemplateColumn Header="Price">
    <DataGridTemplateColumn.CellTemplate>
    <DataTemplate>
    <TextBlock Text="{Binding Price, StringFormat=##.00}"/>
    </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
    <DataGridTemplateColumn.CellEditingTemplate>
    <DataTemplate xmlns:local="clr-namespace:SampleGrid">
    <TextBox>
    <TextBox.Text>
    <Binding Path="Price" StringFormat="##.00">
    <Binding.ValidationRules>
    <local:MyValidationRule ValidationStep="RawProposedValue"/>
    </Binding.ValidationRules>
    </Binding>
    </TextBox.Text>
    </TextBox>
    </DataTemplate>
    </DataGridTemplateColumn.CellEditingTemplate>
    </DataGridTemplateColumn>
    <!--<DataGridTextColumn Header="Price"
    Binding="{Binding Price, StringFormat=##.00}" />-->
    Then the value won't get rounded. Of course you can still not set the double source property to 9999999999999999 though.
    There is no property that you can set on the DataGrid to prevent the value from getting rounded.
    Hope that helps. 
    Please remember to helpful posts as answer to close the thread and then start a new thread if you have a new question.

  • TextBlock does not aligns to right in DataGridTemplateColumn

    Hello guys here:
    I am currently running into a nasty issue. What I wanna achieve is to put two text blocks horizontally in a DataGridTemplateColumn and I wanna align the right text block text to the right. Here is my code:
    <DataGrid ItemsSource="{Binding Path=DVHParameters}"
                                        AutoGenerateColumns="False" 
                                        CanUserResizeColumns="False"
                                        CanUserSortColumns="False"
                                        CanUserReorderColumns="False"
                                        CanUserResizeRows="False"
                                        CanUserAddRows="False"
                                        CanUserDeleteRows="False"
                                        IsHitTestVisible="False"
                                        Visibility="{Binding DVHParametersVisibility}"
                                        Margin="0,0,0,8"
                                        Background="Transparent">
                                    <DataGrid.Columns>
                                        <DataGridTemplateColumn Header="                  ">
                                            <DataGridTemplateColumn.CellTemplate>
                                                <DataTemplate>
                                                    <StackPanel Orientation="Horizontal" HorizontalAlignment="Stretch"
    >
                                                        <TextBlock Text="{Binding Parameter}" HorizontalAlignment="Left"/>
                                                        <TextBlock Margin="1,0,0,0" Foreground="Gray" Text="{Binding
    ValueUnit}"
                                                            HorizontalAlignment="Stretch" TextAlignment="Right"/>
                                                    </StackPanel>
                                                </DataTemplate>
                                            </DataGridTemplateColumn.CellTemplate>
                                        </DataGridTemplateColumn>
                                        <DataGridTextColumn Header="{x:Static local:TextResources.Prescribed}"
                                            Binding="{Binding Prescribed}"/>
                                        <DataGridTextColumn Header="{x:Static local:TextResources.Actual}" 
                                            Binding="{Binding Actual, StringFormat=F1}">
                                            <DataGridTextColumn.CellStyle>
                                                <Style TargetType="DataGridCell" BasedOn="{StaticResource DataGridCellStyle}">
                                                    <Style.Triggers>
                                                        <DataTrigger Binding="{Binding IsConformObjective}" Value="false">
                                                            <Setter Property="Foreground" Value="Red"/>
                                                            <Setter Property="FontWeight" Value="Bold"/>
                                                        </DataTrigger>
                                                    </Style.Triggers>
                                                </Style>
                                            </DataGridTextColumn.CellStyle>
                                        </DataGridTextColumn>
                                    </DataGrid.Columns>
                                </DataGrid>
    Any hints on how to fix this problem and control the width of the textblock in a DataGridTemplateColumn? Thanks in advance!
    Best regards

    I suggest you consider dockpanel because I think you can dock one textblock left and one right.
    Horzontalalignment stretch tries to stretch it to fit the container, don't use that.
    Bear in mind though that you could conceivably end up with one on top of the other if they don't fit.
    A grid with 2 columns might be safer.
    That'd look roughly like
    <DataGridTemplateColumn.CellTemplate>
    <DataTemplate>
    <toolkit:DockPanel >
    <TextBlock .... toolkit:DockPanel.Dock="Left"/>
    <TextBlock .... toolkit:DockPanel.Dock="Right"/>
    </StackPanel>
    </DataTemplate>
    You need a reference and xmlns 
    xmlns:toolkit="http://schemas.microsoft.com/winfx/2006/xaml/presentation/toolkit"
    or
    xmlns:toolkit="clr-namespace:Microsoft.Windows.Controls;assembly=Microsoft.Windows.Controls"
    Hope that helps.
    Recent Technet articles:
    Property List Editing;  
    Dynamic XAML

  • Datagrid: Can I set a tranparency level for column background color?

    Hi all,
    I have a datagrid with background colors set using triggers. This works. I would like to set a column background color but I don't want to make the color solid because it will block the row color. Is there a way to set the column background color transparency
    to 50% (or less) so that I can still see (or blend) with the row background color? I can set the "background" property of the column to a value of "transparent" but this makes no sense without a color.
    Thanks
    <DataGrid.RowStyle>
    <Style TargetType="DataGridRow">
    <Style.Triggers>
    <DataTrigger Binding="{Binding col_oPutorCall}" Value="call">
    <Setter Property="Background" Value="Cornsilk"/>
    </DataTrigger>
    <DataTrigger Binding="{Binding col_oPutorCall}" Value="put">
    <Setter Property="Background" Value="BlanchedAlmond"/>
    </DataTrigger>
    <DataTrigger Binding="{Binding col_rowColor}" Value="false">
    <Setter Property="Background" Value="LightGreen"/>
    </DataTrigger>
    </Style.Triggers>
    </Style>
    </DataGrid.RowStyle>
    <DataGridTextColumn Binding="{Binding col_oBid, StringFormat=F2}" FontFamily="Arial" FontWeight="Bold" FontSize="12" Header="oB" >
    <DataGridTextColumn.CellStyle>
    <Style TargetType="DataGridCell">
    <Setter Property="Background" Value= "Transparent" />
    <Setter Property="Background" Value= "AliceBlue" />
    </Style>
    </DataGridTextColumn.CellStyle>
    </DataGridTextColumn>

    Background is a brush.
    You can define a brush with an opacity in a resourcedictionary merged in app.xaml or in your window.resources ( etc ).
    <Grid.Resources>
    <SolidColorBrush x:Key="TransparentIshBrush" Color="Red" Opacity=".3" />
    </Grid.Resources>
    I should think you can then do:
    <DataGridTextColumn Binding="{Binding col_oBid, StringFormat=F2}" FontFamily="Arial" FontWeight="Bold" FontSize="12" Header="oB" >
    <DataGridTextColumn.CellStyle>
    <Style TargetType="DataGridCell">
    <Setter Property="Background" Value="{StaticResource TransparentIshBrush}" />
    </Style>
    </DataGridTextColumn.CellStyle>
    </DataGridTextColumn>
    The problem with your former piece of code is that setting an opacity on a datagridcell gets everything in it. You would have to do
    <Setter Property="(BackGround.Opacity)"
    And I'm rather doubtful that would work anyhow.
    Please don't forget to upvote posts which you like and mark those which answer your question.
    My latest Technet article - Dynamic XAML

  • TwoWay binding doesn't work using StringFormat={}{#:#.####}, why and how to fix it?

    <TextBox Text="{Binding doResult,UpdateSourceTrigger=PropertyChanged,StringFormat={}{#:#.####},Mode=TwoWay}" Grid.Row="8" Grid.Column="1" Visibility="{Binding ODvisbility,Converter={StaticResource BooleanToVisibilityConverter}}" Style="{Binding ODStyle}"/>
    After changing the stringFormat from 0:0.#### to #:#.#### twoWay binding has stop responding.  
    I fixed one problem and end up with another!

    It is hard to say without having seen all of your code. The information in your last post says nothing but there seems to be nothing wrong with the StringFormat as the property gets set as expected using the sample code I posted. You can try it for yourself
    if you don't believe.
    Please upload a reproducable sample of your issue to OneDrive and post the link to it here if you want anyone to be able to be able to get a clue on what is going on in your application.
    Edit:
    Now I see, it is the target property doesn't get set correcty. Please describe your issue in a bit more detail in the future :)
    Well, StringFormat and UpdateSourceTrigger=PropertyChanged is not a really good combination all the time. You should probably remove the StringFormat and try to handle the formatting logic yourself by for example using a converter. Something like this:
    class DoubleConverter : IValueConverter
    bool addDecimalPoint;
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
    double d = (double)value;
    string s = d.ToString("#.##", System.Globalization.CultureInfo.InvariantCulture);
    if (addDecimalPoint) {
    s += ".";
    addDecimalPoint = false;
    return s;
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
    string s = value.ToString();
    if (s.EndsWith(".")) {
    s += "0";
    addDecimalPoint = true;
    double d;
    if (double.TryParse(s, System.Globalization.NumberStyles.AllowDecimalPoint, System.Globalization.CultureInfo.InvariantCulture, out d))
    return d;
    return value;
    <TextBox Text="{Binding doResult,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay, Converter={StaticResource doubleConverter}}" />
    Please refer to the following page for more information about converters:
    https://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter(v=vs.110).aspx
    Using StringFormat and UpdateSourceTrigger=PropertyChanged  will probably not work anyway.
    Please remember to mark helpful posts as answer and/or helpful.

  • Applying StringFormat to TextBox after left focus in debug mode

    I have simple view: 
    <Grid x:Name="LayoutRoot" Background="White">
    <StackPanel Orientation="Horizontal" Margin="5" Height="50">
    <TextBox Text="{Binding ValueDouble, Mode=TwoWay, StringFormat='\{0:N2\}'}" Width="50" Margin="5" x:Name="TextBox1"></TextBox>
    <TextBox ></TextBox>
    </StackPanel>
    </Grid>
    and simple ViewModel:
    public class MainViewModel : INotifyPropertyChanged
    private double _valueDouble;
    public double ValueDouble
    get { return _valueDouble; }
    set
    _valueDouble = value;
    OnPropertyChanged("ValueDouble");
    public event PropertyChangedEventHandler PropertyChanged;
    [NotifyPropertyChangedInvocator]
    protected virtual void OnPropertyChanged(string propertyName)
    var handler = PropertyChanged;
    if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    If I run application with debugging, after first TextBox has lost focus value stay the same. For example, I has input 42, and after lost focus it still
    42.
    But if I detach debugger, after first TextBox has lost focus applying correct format. For example, I has input 42, and after lost focus it stay 42.00. 
    It very weird and difficult to debug. How to make it works the same in both cases?

    There was a similar question a while ago.
    IIRC the conclusion was you have to delay the raising of property changed.
    Assuming this is the same sort of thing.
    Very slightly will do.
    Storyboard sb = new Storyboard();
    sb.Duration = new TimeSpan(0, 0, 0,0,10);
    sb.Completed += new EventHandler(delegate(object s, EventArgs a)
    OnPropertyChanged("ValueDouble");
    sb.Begin();
    Hope that helps.
    Recent Technet articles: Property List Editing;
    Dynamic XAML

  • MB5B Report table for Open and Closing stock on date wise

    Hi Frds,
    I am trying get values of Open and Closing stock on date wise form the Table MARD and MBEW -Material Valuation but it does not match with MB5B reports,
    Could anyone suggest correct table to fetch the values Open and Closing stock on date wise for MB5B reports.
    Thanks
    Mohan M

    Hi,
    Please check the below links...
    Query for Opening And  Closing Stock
    Inventory Opening and Closing Stock
    open stock and closing stock
    Kuber

  • Report for open and shipped qty

    hi,
    any standard report to show open and shipped qty by SO no.?
    pls advice. thanks

    Hi jojo
    For list of open orders t.code is VA05
    Incomplete delivery - V_UC 
    Reward if useful
    Regards
    Srinath
    Edited by: sri nath on Apr 16, 2008 10:31 PM

  • Wrong 'mini dvi to video' adapter for my 12" Powerbook 1.33

    I recently bought the M9319 mini dvi - video adapter for my 12" Powerbook 1.33 to find that the mini dvi on the adapter is a different size to the one on the computer and the adapters supplied with the computer.
    I've been doing a bit of research into this and it seems a bit of a grey area. Apple have not made it clear in advertising this product that it is only suitable for the newest 12" Powerbooks and even state that it will work with a 1.33 machine in their following article:
    http://docs.info.apple.com/article.html?artnum=86507
    Has anyone had a similar experience, or suggest an alternative product that will work? Did Apple make an older version that works with the 1.33?
    Any help would be much appreciated. Thanks, Graeme.

    Just took the adapter to my local Apple store and they identified it as a mini VGA to video adapter - not what it said on the packaging!
    I've noticed a few posts with this problem, so just double check before you leave the store that the packaging matches the product.

  • Apple Mini-DVI to Video Adapter for eMac ?

    Hi,
    I use an Apple Mini DVI to VGA on my eMac to expand my monitor space, connect to an old Pinceton 15" lcd, both are on 1024 x 768 res in millions colors, and work fine.
    My question is I have plan to buy an Apple Mini-DVI to Video Adapter since some of my project require a transfer process to an old vcr or Sony TRV-27 mini dv cam.
    Would the adapter compatible for my eMac mini DVI port ? because eMac is not mentioned as apple compatible for this adapter at apple store, yet there is a review said it work great on ones eMac.
    Anybody else using this adapter that would share with me ?
    Thank you.

    look like it is indeed an apple mini vga adapter that I use, and now I need an adapter that allow me to connect to a TV, VCR or Mini-DV camcorder.
    will that Apple Mini-DVI to Video adapter compatible to my eMac. Or do they have mini-vga to video adapter on aapple store.
    Thank you any information.

  • Can I purchase Creative Cloud subscriptions for longer than one year at a time?

    I work in the design department of a large business, currently using Creative Suite 6 (Design Standard edition, which includes PS and AI).
    I'd like to get the some of the new CC features, but my manager won't commit to a turnkey month-to-month or even annual rental of Creative Cloud apps (it's a pain for our department's purchaser to have to do orders more than once a year). That said, if they could take care of, say, two years at once, I might get the software. Is this an option? I'm one of only a few folks who use Adobe software (it's not a design business; we're just part of a small design department, and all software purchases need to go through this person, after which they're reimbursed). I'm not interested in any of the extra storage or central administration options that come with the higher priced business subscription.
    Thanks!

    http://www.adobe.com/au/products/creativecloud/faq.html
    Are there any unique benefits that come with my paid membership?
    Yes, as a member of Creative Cloud, you get many benefits that you do not get when you purchase a traditional shrinkwrapped product:
    Access to both the Mac OS and Windows® versions of the desktop applications and the ability to install them on your primary computer and one backup computer. So, if you have a Mac at home and a PC at work, you can install your applications on both as long as they are not running at the same time. See the product license agreements page for more information.

  • Any ideas for a status or "at a glance" splash screen / presentation?

    This is an idea I've been tossing around and wanted to know if there was something easy out there that would accomplish this...
    I'd like to mount a monitor in one of our common areas for the management team and have it display current statuses of some of our IT features/services and maybe quick bits on what we are currently working on, major issues, etc... 
    I've seen some company lobbies with similar setups that display company-wide information, weather, etc.. so I know the capability is out there but I don't know squat regarding what that would entail. The easier, the better, naturally... as I don't want this to turn into an entire job position updating it, haha. But something that I could hopefully remotely update would be nice.
    Any ideas? Thanks!
    This topic first appeared in the Spiceworks Community

    Please see the two articles below:
    http://support.apple.com/kb/TS3694
    http://support.apple.com/kb/TS3125

  • Looking for Daily Calendar At-a-Glance App

    I'd love to find an app that will post an alert to my iPhone each morning listing out my day's calendar events. Anyone know of one? For what it's worth, I have 4 active calendars in Calendar app.

    I don't know of any apps like the one you want; however, there is probably something out there that will do the job. I did want to suggest Google Calendar, which will send you email and SMS reminders about events and things you have put on your calendar. You might already be aware of this, so if you are, just disregard. I just wanted to suggest it in case you weren't aware of it. I use it all the time, and it's very handy. 

  • Can I show a color bar instead of a color bullet in iCal Monthly view for all my events in all calendars?

    In the Monthly view of iCal the only events that show a color bar in the event is the Birthday Calendar. All other events in all my other calendars only show a color bullet next to the event (unless I click on that event which then shows as a color bar). I would like to know if it is possible for all the calendar events to have a color bar in the monthly view instead of just that tiny color bullet.

    Greetings Judith,
    Before making any attempts at deleting calendar data, backup what you have just in case:
    Click on each calendar on the left hand side of iCal one at a time highlighting it's name and then going to File Export > Export and saving the resulting calendar file to a logical location for safekeeping.
    iCal has an automated function located in iCal > Preferences > Advanced > Delete events "X" days after they have passed.  By typing in a value for days you can tell iCal to delete all events before that time frame.
    Example:
    Today is 4-16-2012.
    If I wanted to delete all events prior to 1 year ago (4-16-2011) I would type in "365" for the number of days.
    Once you type in the number of days you want kept in iCal, close the preferences and then quit iCal.
    Re-open iCal and check to see if the events are gone.  If not you may want to leave it open for several minutes and then quit again.
    Once the events are removed go back to  iCal > Preferences > Advanced > Delete events "X" days after they have passed and make sure the check mark is removed to prevent future deletion.
    Hope that helps.

Maybe you are looking for