Search Results

Search found 60 results on 3 pages for 'stringformat'.

Page 1/3 | 1 2 3  | Next Page >

  • WPF StringFormat={0:C} showing as dollars

    - by Coesy
    Why does this line of code <TextBlock Text="{Binding Net, StringFormat=c}"/> Output the result as $xx.xx when all my regional settings are set to UK. I expect it to output it as £xx.xx. Any ideas? I have tried different variations of the stringformat including StringFormat={}{0:C} but still get the same result. Thanks for looking.

    Read the article

  • StringFormat=c showing as dollars

    - by Coesy
    Why does this line of code <TextBlock Text="{Binding Net, StringFormat=c}"/> Output the result as $xx.xx when all my regional settings are set to UK. I expect it to output it as £xx.xx. Any ideas? I have tried different variations of the stringformat including StringFormat={}{0:C} but still get the same result. Thanks for looking.

    Read the article

  • customized StringFormat in WPF DataGrid

    - by Boris Lipschitz
    What would be the most efficient way to set customized formatting of the column in DataGrid. I can't use the following StringFormat, as my sophisticated formatting also depends on some other property of this ViewModel. (e.g Price formatting has some complicated formatting logic based on different markets.) Binding ="{Binding Price, StringFormat='{}{0:#,##0.0##}'}"

    Read the article

  • strange Problem with WPF Textbox stringformat - Cursor moves back

    - by Emad
    I am using WPF 4.0 TextBox and binding. I am using StringFormat to format the number as currency. the XAML looks like this: <TextBox Text="{Binding Path=ValueProperty, ValidatesOnDataErrors=True, ValidatesOnExceptions=True, StringFormat={}{0:C}, UpdateSourceTrigger=PropertyChanged}"> </TextBox> Everything seems to work correctly except for a strange behavior: When for example a user types in 12: right after typing 1, the value in the textbox becomes $1.00 and the weird thing is the the cursor is moved to be between the $ and the 1. So when a user simply types in 12, the result becomes $21.00. How can I fix this strange behavior?

    Read the article

  • WPF Binding.Stringformat ignored

    - by John
    With .NET 3.5 SP 1 I checked out this blog and followed instructions, however the StringFormat parameter still gets ignored. Any possible reasons? To be sure: the datatype that are involved are DateTime, double, int. So the formatting SHOULD work, but it's not. Any clues why?

    Read the article

  • How to format TimeSpan in xaml

    - by biju
    I am trying to format a textblock which is bound to a TimeSpan property.It works if the property is of type DateTime but it fails if it is a TimeSpan .I can get it done using a converter.But i am trying to find out if there is any alternatives. Sample Code public TimeSpan MyTime { get; set; } public Window2() { InitializeComponent(); MyTime = DateTime.Now.TimeOfDay; DataContext = this; } Xaml <TextBlock Text="{Binding MyTime,StringFormat=HH:mm}"/> I am expecting the textblock to show only hours and mintes.But it is showing like 19:10:46.8048860

    Read the article

  • String format or REGEX.

    - by ThePower
    I need an simple way to check whether a string that is sent to my function is of the form: (x + n)(x + m) //the +'s can be minus' //n and m represent a double //x represents the char 'x' Is there a simple string format that I can use to check that this is the form. As opposed to checking each character singularly. The whitespace will be removed to save any confusion. Regards Lloyd

    Read the article

  • QString::number() - zero padding?

    - by elcuco
    I want to "stringify" a number and keep leading zeros. Unlike this question: http://stackoverflow.com/questions/885401/print-trailing-zeros-in-a-qstring I also need this in hex. By code now uses this, which is not enough: QString::number(myNumber,16).toUpper()

    Read the article

  • Check for a string format...

    - by ThePower
    I need an simple way to check whether a string that is sent to my function is of the form: (x + n)(x + m) //the +'s can be minus' //n and m represent a double //x represents the char 'x' Is there a simple string format that I can use to check that this is the form. As opposed to checking each character singularly. The whitespace will be removed to save any confusion. Regards Lloyd

    Read the article

  • Avoiding resource (localizable string) duplication with String.Format

    - by Hrvoje Prgeša
    I'm working on a application (.NET, but not relevant) where there is large potential for resource/string duplication - most of these strings are simple like: Volume: 33 Volume: 33 (dB) Volume 33 dB Volume (dB) Command - Volume: 33 (dB) where X, Y and unit are the same. Should I define a new resource for each of the string or is it preferable to use String.Format to simplify some of these, eg.: String.Format("{0}: {1}", Resource.Volume, 33) String.Format("{0}: {1} {2}", Resource.Volume, 33, Resource.dB) Resource.Volume String.Format("{0} ({1})", 33, Resource.dB) String.Format("{0} ({1})", Resource.Volume, Resource.dB) String.Format("Command - {0}: {1} {2}", Resource.Volume, 33, Resource.dB) I would also define string formats like "{0}: {1}" in the resources so there would be a possibility of reordering words... I would not use this approach selectivly and not throughout the whole application.. And how about: String.Format("{0}: {1}", Volume, Resource.Muted_Volume) // = Volume: Muted Resource.Muted_Volume String.Format("{0}: {1} (by user {2})", Volume, Resource.Muted_Volume, "xy") // = Volume: Muted (by user xy) The advantage is cutting the number of resource by the factor of 4-5. Are there any hidden dangers of using this approach? Could someone give me an example (language) where this would not work correctly?

    Read the article

  • javascript error of unterminated string

    - by OM The Eternity
    I want pass a parameter of javascript functiona which is a string. This javascript function is a hintbox on mousehover.. and the string i am using is like this: Hemmed Finish: Every side/edge (1/2" to 2") of the banner are folded and glued (special vinyl solution) or heat pressed. This is the most common and best finish option. Stitched Finish: Every side/edge (1" to 2") of the banner are folded in the back and stitched/sewed with white thread. This is not a common option as thread can be seen on the banner. Now in the hintbox on mousehover the above given text has to be display as it is displayed above along with the paragraph break.. But when i pass the above as parameter in that function along with appending some backslashes to recognise some punctuation, iots till gives me javascript error of unterminated string... I am doing this: onMouseover="showhint('Hemmed Finish\: Every side/edge \(1/2\'\' to 2\'\'\) of the banner are folded and glued \(special vinyl solution\) or heat pressed. This is the most common and best finish option.Stitched Finish\: Every side/edge \(1\'\' to 2\'\'\) of the banner are folded in the back and stitched/sewed with white thread. This is not a common option as thread can be seen on the banner', this, event, '250px')" pls could u help me in rectifying the issue...

    Read the article

  • Formatting made easy - Silverlight 4

    - by PeterTweed
    One of the simplest tasks in business apps is displaying different types of data to be read in the format that the user expects them.  In Silverlight versions until Silverlight 4 this has meant using a Converter to format data during binding.  This involves writing code for the formatting of the data to bind, instead of simply defining the formatting to use for the data in question where you bind the data to the control.   In Silverlight 4 we find the addition of the StringFormat markup extension that allows us to do exactly this.  Of course the nice thing is the ability to use the common formatting conventions available in C# through the String.Format function.   This post will show you how to use three of the common formatting conventions - currency, a defined number of decimal places for a number and a date format.   Steps:   1. Create a new Silverlight 4 application   2. In the body of the MainPage.xaml.cs file replace the MainPage class with the following code:       public partial class MainPage : UserControl     {         public MainPage()         {             InitializeComponent();             this.Loaded += new RoutedEventHandler(MainPage_Loaded);         }           void MainPage_Loaded(object sender, RoutedEventArgs e)         {             info i = new info() { PriceValue = new Decimal(9.2567), DoubleValue = 1.2345678, DateValue = DateTime.Now };             this.DataContext = i;         }     }         public class info     {         public decimal PriceValue { get; set; }         public double DoubleValue { get; set; }         public DateTime DateValue { get; set; }     }   This code defines a class called info with different data types for the three properties.  A new instance of the class is created and bound to the DataContext of the page.   3.  In the MainPage.xaml file copy the following XAML into the LayoutRoot grid:           <Grid.RowDefinitions>             <RowDefinition Height="60*" />             <RowDefinition Height="28*" />             <RowDefinition Height="28*" />             <RowDefinition Height="30*" />             <RowDefinition Height="154*" />         </Grid.RowDefinitions>         <Grid.ColumnDefinitions>             <ColumnDefinition Width="86*" />             <ColumnDefinition Width="314*" />         </Grid.ColumnDefinitions>         <TextBlock Grid.Row="1" Height="23" HorizontalAlignment="Left" Margin="32,0,0,0" Name="textBlock1" Text="Price Value:" VerticalAlignment="Top" />         <TextBlock Grid.Row="2" Height="23" HorizontalAlignment="Left" Margin="32,0,0,0" Name="textBlock2" Text="Decimal Value:" VerticalAlignment="Top" />         <TextBlock Grid.Row="3" Height="23" HorizontalAlignment="Left" Margin="32,0,0,0" Name="textBlock3" Text="Date Value:" VerticalAlignment="Top" />         <TextBlock Grid.Column="1" Grid.Row="1" Height="23" HorizontalAlignment="Left" Name="textBlock4" Text="{Binding PriceValue, StringFormat='C'}" VerticalAlignment="Top" Margin="6,0,0,0" />         <TextBlock Grid.Column="1" Grid.Row="2" Height="23" HorizontalAlignment="Left" Margin="6,0,0,0" Name="textBlock5" Text="{Binding DoubleValue, StringFormat='N3'}" VerticalAlignment="Top" />         <TextBlock Grid.Column="1" Grid.Row="3" Height="23" HorizontalAlignment="Left" Margin="6,0,0,0" Name="textBlock6" Text="{Binding DateValue, StringFormat='yyyy MMM dd'}" VerticalAlignment="Top" />   This XAML defines three textblocks that use the StringFormat markup extension.  The three examples use the C for currency, N3 for a number with 3 decimal places and yyy MM dd for a date that displays year 3 letter month and 2 number date.   4. Run the application and see the data displayed with the correct formatting. It's that easy!

    Read the article

  • Techniques to re-factor garbage and maintain sanity?

    - by Incognito
    So I'm sitting down to a nice bowl of c# spaghetti, and need to add something or remove something... but I have challenges everywhere from functions passing arguments that doesn't make sense, someone who doesn't understand data structures abusing strings, redundant variables, some comments are red-hearings, internationalization is on a per-every-output-level, SQL doesn't use any kind of DBAL, database connections are left open everywhere... Are there any tools or techniques I can use to at least keep track of the "functional integrity" of the code (meaning my "improvements" don't break it), or a resource online with common "bad patterns" that explains a good way to transition code? I'm basically looking for a guidebook on how to spin straw into gold. Here's some samples from the same 500 line function: protected void DoSave(bool cIsPostBack) { //ALWAYS a cPostBack cIsPostBack = true; SetPostBack("1"); string inCreate ="~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"; parseValues = new string []{"","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","",""}; if (!cIsPostBack) { //....... //.... //.... if (!cIsPostBack) { } else { } //.... //.... strHPhone = StringFormat(s1.Trim()); s1 = parseValues[18].Replace(encStr," "); strWPhone = StringFormat(s1.Trim()); s1 = parseValues[11].Replace(encStr," "); strWExt = StringFormat(s1.Trim()); s1 = parseValues[21].Replace(encStr," "); strMPhone = StringFormat(s1.Trim()); s1 = parseValues[19].Replace(encStr," "); //(hundreds of lines of this) //.... //.... SQL = "...... lots of SQL .... "; SqlCommand curCommand; curCommand = new SqlCommand(); curCommand.Connection = conn1; curCommand.CommandText = SQL; try { curCommand.ExecuteNonQuery(); } catch {} //.... } I've never had to refactor something like this before, and I want to know if there's something like a guidebook or knowledgebase on how to do this sort of thing, finding common bad patterns and offering the best solutions to repair them. I don't want to just nuke it from orbit,

    Read the article

  • Generating radial indicator images using C#

    - by DigiMortal
    In one of my projects I needed to draw radial indicators for processes measured in percent. Simple images like the one shown on right. I solved the problem by creating images in C# and saving them on server hard disc so if image is once generated then it is returned from disc next time. I am not master of graphics or geometrics but here is the code I wrote. Drawing radial indicator To get things done quick’n’easy way – later may some of younger developers be the one who may need to changes things – I divided my indicator drawing process to four steps shown below. 1. Fill pie 2. Draw circles 3. Fill inner circle 4. Draw text Drawing image Here is the code to draw indicators. private static void SaveRadialIndicator(int percent, string filePath) {     using (Bitmap bitmap = new Bitmap(100, 100))     using (Graphics objGraphics = Graphics.FromImage(bitmap))     {         // Initialize graphics         objGraphics.Clear(Color.White);         objGraphics.SmoothingMode = SmoothingMode.AntiAlias;         objGraphics.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;           // Fill pie         // Degrees are taken clockwise, 0 is parallel with x         // For sweep angle we must convert percent to degrees (90/25 = 18/5)         float startAngle = -90.0F;                        float sweepAngle = (18.0F / 5) * percent;           Rectangle rectangle = new Rectangle(5, 5, 90, 90);         objGraphics.FillPie(Brushes.Orange, rectangle, startAngle, sweepAngle);           // Draw circles         rectangle = new Rectangle(5, 5, 90, 90);         objGraphics.DrawEllipse(Pens.LightGray, rectangle);         rectangle = new Rectangle(20, 20, 60, 60);         objGraphics.DrawEllipse(Pens.LightGray, rectangle);           // Fill inner circle with white         rectangle = new Rectangle(21, 21, 58, 58);         objGraphics.FillEllipse(Brushes.White, rectangle);           // Draw text on image         // Use rectangle for text and align text to center of rectangle         var font = new Font("Arial", 13, FontStyle.Bold);         StringFormat stringFormat = new StringFormat();         stringFormat.Alignment = StringAlignment.Center;         stringFormat.LineAlignment = StringAlignment.Center;           rectangle = new Rectangle(20, 40, 62, 20);         objGraphics.DrawString(percent + "%", font, Brushes.DarkGray, rectangle, stringFormat);           // Save indicator to file         objGraphics.Flush();         if (File.Exists(filePath))             File.Delete(filePath);           bitmap.Save(filePath, ImageFormat.Png);     }        } Using indicators on web page To show indicators on your web page you can use the following code on page that outputs indicator images: protected void Page_Load(object sender, EventArgs e) {     var percentString = Request.QueryString["percent"];     var percent = 0;     if(!int.TryParse(percentString, out percent))         return;     if(percent < 0 || percent > 100)         return;       var file = Server.MapPath("~/images/percent/" + percent + ".png");     if(!File.Exists(file))         SaveImage(percent, file);       Response.Clear();     Response.ContentType = "image/png";     Response.WriteFile(file);     Response.End(); } Om your pages where you need indicator you can set image source to Indicator.aspx (if you named your indicator handling file like this) and add percent as query string:     <img src="Indicator.aspx?percent=30" /> That’s it! If somebody knows simpler way how to generate indicators like this I am interested in your feedback.

    Read the article

  • WPF Edit hours and minutes of a DateTime

    - by PaN1C_Showt1Me
    Hi ! I have 3 TextBoxes to edit a DateTime. One to edit the Date and 2 to edit hour and minutes. How would you do that? The code below doesn't reflect the DateTime changes when editing the hour or minute: <TextBox Text="{Binding MyDateTime}" /> <TextBox Text="{Binding MyDateTime, StringFormat=\{0:HH\}}}" /> <TextBox Text="{Binding MyDateTime}, StringFormat=\{0:mm\}}" />

    Read the article

  • Graphics.MeasureCharacterRanges giving wrong size calculations in C#.Net?

    - by Owen Blacker
    I'm trying to render some text into a specific part of an image in a Web Forms app. The text will be user entered, so I want to vary the font size to make sure it fits within the bounding box. I have code that was doing this fine on my proof-of-concept implementation, but I'm now trying it against the assets from the designer, which are larger, and I'm getting some odd results. I'm running the size calculation as follows: StringFormat fmt = new StringFormat(); fmt.Alignment = StringAlignment.Center; fmt.LineAlignment = StringAlignment.Near; fmt.FormatFlags = StringFormatFlags.NoClip; fmt.Trimming = StringTrimming.None; int size = __startingSize; Font font = __fonts.GetFontBySize(size); while (GetStringBounds(text, font, fmt).IsLargerThan(__textBoundingBox)) { context.Trace.Write("MyHandler.ProcessRequest", "Decrementing font size to " + size + ", as size is " + GetStringBounds(text, font, fmt).Size() + " and limit is " + __textBoundingBox.Size()); size--; if (size < __minimumSize) { break; } font = __fonts.GetFontBySize(size); } context.Trace.Write("MyHandler.ProcessRequest", "Writing " + text + " in " + font.FontFamily.Name + " at " + font.SizeInPoints + "pt, size is " + GetStringBounds(text, font, fmt).Size() + " and limit is " + __textBoundingBox.Size()); I then use the following line to render the text onto an image I'm pulling from the filesystem: g.DrawString(text, font, __brush, __textBoundingBox, fmt); where: __fonts is a PrivateFontCollection, PrivateFontCollection.GetFontBySize is an extension method that returns a FontFamily RectangleF __textBoundingBox = new RectangleF(150, 110, 212, 64); int __minimumSize = 8; int __startingSize = 48; Brush __brush = Brushes.White; int size starts out at 48 and decrements within that loop Graphics g has SmoothingMode.AntiAlias and TextRenderingHint.AntiAlias set context is a System.Web.HttpContext (this is an excerpt from the ProcessRequest method of an IHttpHandler) The other methods are: private static RectangleF GetStringBounds(string text, Font font, StringFormat fmt) { CharacterRange[] range = { new CharacterRange(0, text.Length) }; StringFormat myFormat = fmt.Clone() as StringFormat; myFormat.SetMeasurableCharacterRanges(range); using (Graphics g = Graphics.FromImage(new Bitmap( (int) __textBoundingBox.Width - 1, (int) __textBoundingBox.Height - 1))) { g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias; Region[] regions = g.MeasureCharacterRanges(text, font, __textBoundingBox, myFormat); return regions[0].GetBounds(g); } } public static string Size(this RectangleF rect) { return rect.Width + "×" + rect.Height; } public static bool IsLargerThan(this RectangleF a, RectangleF b) { return (a.Width > b.Width) || (a.Height > b.Height); } Now I have two problems. Firstly, the text sometimes insists on wrapping by inserting a line-break within a word, when it should just fail to fit and cause the while loop to decrement again. I can't see why it is that Graphics.MeasureCharacterRanges thinks that this fits within the box when it shouldn't be word-wrapping within a word. This behaviour is exhibited irrespective of the character set used (I get it in Latin alphabet words, as well as other parts of the Unicode range, like Cyrillic, Greek, Georgian and Armenian). Is there some setting I should be using to force Graphics.MeasureCharacterRanges only to be word-wrapping at whitespace characters (or hyphens)? This first problem is the same as post 2499067. Secondly, in scaling up to the new image and font size, Graphics.MeasureCharacterRanges is giving me heights that are wildly off. The RectangleF I am drawing within corresponds to a visually apparent area of the image, so I can easily see when the text is being decremented more than is necessary. Yet when I pass it some text, the GetBounds call is giving me a height that is almost double what it's actually taking. Using trial and error to set the __minimumSize to force an exit from the while loop, I can see that 24pt text fits within the bounding box, yet Graphics.MeasureCharacterRanges is reporting that the height of that text, once rendered to the image, is 122px (when the bounding box is 64px tall and it fits within that box). Indeed, without forcing the matter, the while loop iterates to 18pt, at which point Graphics.MeasureCharacterRanges returns a value that fits. The trace log excerpt is as follows: Decrementing font size to 24, as size is 193×122 and limit is 212×64 Decrementing font size to 23, as size is 191×117 and limit is 212×64 Decrementing font size to 22, as size is 200×75 and limit is 212×64 Decrementing font size to 21, as size is 192×71 and limit is 212×64 Decrementing font size to 20, as size is 198×68 and limit is 212×64 Decrementing font size to 19, as size is 185×65 and limit is 212×64 Writing VENNEGOOR of HESSELINK in DIN-Black at 18pt, size is 178×61 and limit is 212×64 So why is Graphics.MeasureCharacterRanges giving me a wrong result? I could understand it being, say, the line height of the font if the loop stopped around 21pt (which would visually fit, if I screenshot the results and measure it in Paint.Net), but it's going far further than it should be doing because, frankly, it's returning the wrong damn results. Any and all help gratefully received. Thanks!

    Read the article

  • Silverlight Cream for May 30, 2010 -- #873

    - by Dave Campbell
    In this Issue: Matthias Shapiro, Colin Blair(-2-), Mike Snow, Marlon Grech, Victor Gaudioso. Shoutout: If you're going to be anywhere near Mission Viejo, California on June 19th, set your calendar for this Victor Gaudioso event: New Speaking Event: Microsoft Book Signing/Silverlight 4 Presentation SilverLaw has another example of his Flexible surface app up: Drag & Drop Flexible Surface - Silverlight 4 From SilverlightCream.com: Silverlight 4 Binding and StringFormat in XAML Matthias Shapiro has a discussion posted about StringFormat binding in Silverlight 4 ... he dug in hard on this... well worth a read. View Model Collection Properties for WCF RIA Services Colin Blair is discussing some possibilities for exposing collections of entities from the ViewModel... his favorite: PagedCollectionView. The next post discusses this deeper. Advanced Paged Collection View Colin Blair continues in more depth on the PagedCollectionView, this time handling paging, sorting, and multiple loads. Silverlight Tip of the day #25 – Detecting Validation Errors on Submit Mike Snow's latest Tip of the Day is up and is about validation - specifically validating after your user has pressed "OK" INotifyPropertyChanged… I am fed up of handling events just to know when a property changed Marlon Grech has an Rx-less solution to code notifications of properties changing... this is a WPF and Silverlight solution and all the code is downloadable. New Silverlight Video Tutorial: How to Add Multiple BitmapEffects to One Object Victor Gaudioso's latest outing is in response to a query from a reader and is a video tutorial showing how to add multiple bitmap effects to one object. Stay in the 'Light! Twitter SilverlightNews | Twitter WynApse | WynApse.com | Tagged Posts | SilverlightCream Join me @ SilverlightCream | Phoenix Silverlight User Group Technorati Tags: Silverlight    Silverlight 3    Silverlight 4    Windows Phone MIX10

    Read the article

  • WPF items not visible when grouping is applied

    - by Tri Q
    Hi, I'm having this strange issue with my ItemsControl grouping. I have the following setup: <ItemsControl Margin="3" ItemsSource="{Binding Communications.View}" > <ItemsControl.GroupStyle> <GroupStyle> <GroupStyle.ContainerStyle> <Style TargetType="{x:Type GroupItem}"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type GroupItem}"> <Expander> <Expander.Header> <Grid> <Grid.ColumnDefinitions > <ColumnDefinition Width="*" /> <ColumnDefinition Width="Auto" /> </Grid.ColumnDefinitions> <TextBlock Text="{Binding ItemCount, StringFormat='{}[{0}] '}" FontWeight="Bold" /> <TextBlock Grid.Column="1" Text="{Binding Name, Converter={StaticResource GroupingFormatter}, StringFormat='{}Subject: {0}'}" FontWeight="Bold" /> </Grid> </Expander.Header> <ItemsPresenter /> </Expander> </ControlTemplate> </Setter.Value> </Setter> </Style> </GroupStyle.ContainerStyle> </GroupStyle> </ItemsControl.GroupStyle> <ItemsControl.ItemTemplate> <DataTemplate> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="*" /> <ColumnDefinition Width="Auto" /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition /> <RowDefinition /> </Grid.RowDefinitions> <TextBlock FontWeight="Bold" Text="{Binding Inspector, Converter={StaticResource NameFormatter}, StringFormat='{}From {0}:'}" Margin="3" /> <TextBlock Text="{Binding SentDate, StringFormat='{}{0:dd/MM/yy}'}" Grid.Row="1" Margin="3"/> <TextBlock Text="{Binding Message }" Grid.Column="1" Grid.RowSpan="2" Margin="3"/> <Button Command="vm:CommunicationViewModel.DeleteMessageCommand" CommandParameter="{Binding}" HorizontalAlignment="Right" Grid.Column="2">Delete</Button> </Grid> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> In my ViewModel, I expose a CollectionViewSource named 'Communications'. I proceed to adding a grouping patter like so: Communications.GroupDescriptions.Add(new PropertyGroupDescription("Subject")); Now, the problem i'm experience is the grouping work fine, but I can't see any items inside the groups. What am I doing wrong? Any pointers would be much appreciated.

    Read the article

  • C#: Graphics DrawString to Exactly Place Text on a System.Label

    - by jp2code
    I have overridden the OnPaint method of my Label control in VS2008: void Label_OnPaint(object sender, PaintEventArgs e) { base.OnPaint(e); Label lbl = sender as Label; if (lbl != null) { string Text = lbl.Text; e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; if (myShowShadow) { // draw the shadow first! e.Graphics.DrawString(Text, lbl.Font, new SolidBrush(myShadowColor), myShadowOffset, StringFormat.GenericDefault); } e.Graphics.DrawString(Text, lbl.Font, new SolidBrush(lbl.ForeColor), 0, 0, StringFormat.GenericDefault); } } This works, but I really want to find out how to center the text both vertically and horizontally. I've heard of the MeasureString() method, but my "Text" complicates matters because it could include page breaks. Could someone guide me with how to do this?

    Read the article

  • Resharper and var

    - by Refracted Paladin
    I have Resharper 4.5 and have found it invaluable so far but I have a concern; It seems to want to make every variable declaration implicit(var). As a relativly new developer how much should I trust ReSharper when it comes to this? Take the below code snippet from a method that Paints Tab Headers. TabPage currentTab = tabCaseNotes.TabPages[e.Index]; Rectangle itemRect = tabCaseNotes.GetTabRect(e.Index); SolidBrush fillBrush = new SolidBrush(Color.Linen); SolidBrush textBrush = new SolidBrush(Color.Black); StringFormat sf = new StringFormat { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center }; Resharper wants me to change all 5 of those to var. I have read the following similar post,Use of var keyword in C#, but I would like to know from a Resharper standpoint. Thanks!

    Read the article

  • How do I remove the time from printpreview dialog?

    - by Albo Best
    Here is my code: Imports System.Data.OleDb Imports System.Drawing.Printing Namespace Print Public Class Form1 Inherits System.Windows.Forms.Form Dim PrintC As PrinterClass Dim conn As OleDb.OleDbConnection Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=..\\db1.mdb" Dim sql As String = String.Empty Dim ds As DataSet Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load FillDataGrid() '//create printerclass object PrintC = New PrinterClass(PrintDocument1, dataGrid) End Sub Private Sub FillDataGrid() Try Dim dt As New DataTable Dim ds As New DataSet ds.Tables.Add(dt) Dim da As New OleDbDataAdapter con.Open() da = New OleDbDataAdapter("SELECT * from klient ", con) da.Fill(dt) con.Close() dataGrid.DataSource = dt.DefaultView Dim dTable As DataTable For Each dTable In ds.Tables Dim dgStyle As DataGridTableStyle = New DataGridTableStyle dgStyle.MappingName = dTable.TableName dataGrid.TableStyles.Add(dgStyle) Next ' DataGrid settings dataGrid.CaptionText = "TE GJITHE KLIENTET" dataGrid.HeaderFont = New Font("Verdana", 12) dataGrid.TableStyles(0).GridColumnStyles(0).Width = 60 dataGrid.TableStyles(0).GridColumnStyles(1).Width = 140 dataGrid.TableStyles(0).GridColumnStyles(2).Width = 140 dataGrid.TableStyles(0).GridColumnStyles(3).Width = 140 dataGrid.TableStyles(0).GridColumnStyles(4).Width = 140 dataGrid.TableStyles(0).GridColumnStyles(5).HeaderText = "" dataGrid.TableStyles(0).GridColumnStyles(5).Width = -1 Catch ex As Exception MessageBox.Show(ex.Message) End Try End Sub Private Sub btnPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrint.Click 'create printerclass object PrintC = New PrinterClass(PrintDocument1, dataGrid) PrintDocument1.Print() End Sub Private Sub btnPreview_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPreview.Click 'create printerclass object PrintC = New PrinterClass(PrintDocument1, dataGrid) ''preview Dim ps As New PaperSize("A4", 840, 1150) ps.PaperName = PaperKind.A4 PrintDocument1.DefaultPageSettings.PaperSize = ps PrintPreviewDialog1.WindowState = FormWindowState.Normal PrintPreviewDialog1.StartPosition = FormStartPosition.CenterScreen PrintPreviewDialog1.ClientSize = New Size(600, 600) PrintPreviewDialog1.ShowDialog() End Sub Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage 'print grid Dim morepages As Boolean = PrintC.Print(e.Graphics) If (morepages) Then e.HasMorePages = True End If End Sub End Class End Namespace This is how data looks in DataGrid (that's perfect)... and here is how it looks when I click PrintPreview. (I don't want the time to appear there, the "12:00:00" part. in database the date is stored as Short Date (10-Dec-12) Can somebody suggest a way around that? Imports System Imports System.Windows.Forms Imports System.Drawing Imports System.Drawing.Printing Imports System.Collections Imports System.Data Namespace Print Public Class PrinterClass '//clone of Datagrid Dim PrintGrid As Grid '//printdocument for initial printer settings Private PrintDoc As PrintDocument '//defines whether the grid is ordered right to left Private bRightToLeft As Boolean '//Current Top Private CurrentY As Single = 0 '//Current Left Private CurrentX As Single = 0 '//CurrentRow to print Private CurrentRow As Integer = 0 '//Page Counter Public PageCounter As Integer = 0 '/// <summary> '/// Constructor Class '/// </summary> '/// <param name="pdocument"></param> '/// <param name="dgrid"></param> Public Sub New(ByVal pdocument As PrintDocument, ByVal dgrid As DataGrid) 'MyBase.new() PrintGrid = New Grid(dgrid) PrintDoc = pdocument '//The grid columns are right to left bRightToLeft = dgrid.RightToLeft = RightToLeft.Yes '//init CurrentX and CurrentY CurrentY = pdocument.DefaultPageSettings.Margins.Top CurrentX = pdocument.DefaultPageSettings.Margins.Left End Sub Public Function Print(ByVal g As Graphics, ByRef currentX As Single, ByRef currentY As Single) As Boolean '//use predefined area currentX = currentX currentY = currentY PrintHeaders(g) Dim Morepages As Boolean = PrintDataGrid(g) currentY = currentY currentX = currentX Return Morepages End Function Public Function Print(ByVal g As Graphics) As Boolean CurrentX = PrintDoc.DefaultPageSettings.Margins.Left CurrentY = PrintDoc.DefaultPageSettings.Margins.Top PrintHeaders(g) Return PrintDataGrid(g) End Function '/// <summary> '/// Print the Grid Headers '/// </summary> '/// <param name="g"></param> Private Sub PrintHeaders(ByVal g As Graphics) Dim sf As StringFormat = New StringFormat '//if we want to print the grid right to left If (bRightToLeft) Then CurrentX = PrintDoc.DefaultPageSettings.PaperSize.Width - PrintDoc.DefaultPageSettings.Margins.Right sf.FormatFlags = StringFormatFlags.DirectionRightToLeft Else CurrentX = PrintDoc.DefaultPageSettings.Margins.Left End If Dim i As Integer For i = 0 To PrintGrid.Columns - 1 '//set header alignment Select Case (CType(PrintGrid.Headers.GetValue(i), Header).Alignment) Case HorizontalAlignment.Left 'left sf.Alignment = StringAlignment.Near Case HorizontalAlignment.Center sf.Alignment = StringAlignment.Center Case HorizontalAlignment.Right sf.Alignment = StringAlignment.Far End Select '//advance X according to order If (bRightToLeft) Then '//draw the cell bounds (lines) and back color g.FillRectangle(New SolidBrush(PrintGrid.HeaderBackColor), CurrentX - PrintGrid.Headers(i).Width, CurrentY, PrintGrid.Headers(i).Width, PrintGrid.Headers(i).Height) g.DrawRectangle(New Pen(PrintGrid.LineColor), CurrentX - PrintGrid.Headers(i).Width, CurrentY, PrintGrid.Headers(i).Width, PrintGrid.Headers(i).Height) '//draw the cell text g.DrawString(PrintGrid.Headers(i).CText, PrintGrid.Headers(i).Font, New SolidBrush(PrintGrid.HeaderForeColor), New RectangleF(CurrentX - PrintGrid.Headers(i).Width, CurrentY, PrintGrid.Headers(i).Width, PrintGrid.Headers(i).Height), sf) '//next cell CurrentX -= PrintGrid.Headers(i).Width Else '//draw the cell bounds (lines) and back color g.FillRectangle(New SolidBrush(PrintGrid.HeaderBackColor), CurrentX, CurrentY, PrintGrid.Headers(i).Width, PrintGrid.Headers(i).Height) g.DrawRectangle(New Pen(PrintGrid.LineColor), CurrentX, CurrentY, PrintGrid.Headers(i).Width, PrintGrid.Headers(i).Height) '//draw the cell text g.DrawString(PrintGrid.Headers(i).CText, PrintGrid.Headers(i).Font, New SolidBrush(PrintGrid.HeaderForeColor), New RectangleF(CurrentX, CurrentY, PrintGrid.Headers(i).Width, PrintGrid.Headers(i).Height), sf) '//next cell CurrentX += PrintGrid.Headers(i).Width End If Next '//reset to beginning If (bRightToLeft) Then '//right align CurrentX = PrintDoc.DefaultPageSettings.PaperSize.Width - PrintDoc.DefaultPageSettings.Margins.Right Else '//left align CurrentX = PrintDoc.DefaultPageSettings.Margins.Left End If '//advance to next row CurrentY = CurrentY + CType(PrintGrid.Headers.GetValue(0), Header).Height End Sub Private Function PrintDataGrid(ByVal g As Graphics) As Boolean Dim sf As StringFormat = New StringFormat PageCounter = PageCounter + 1 '//if we want to print the grid right to left If (bRightToLeft) Then CurrentX = PrintDoc.DefaultPageSettings.PaperSize.Width - PrintDoc.DefaultPageSettings.Margins.Right sf.FormatFlags = StringFormatFlags.DirectionRightToLeft Else CurrentX = PrintDoc.DefaultPageSettings.Margins.Left End If Dim i As Integer For i = CurrentRow To PrintGrid.Rows - 1 Dim j As Integer For j = 0 To PrintGrid.Columns - 1 '//set cell alignment Select Case (PrintGrid.Cell(i, j).Alignment) '//left Case HorizontalAlignment.Left sf.Alignment = StringAlignment.Near Case HorizontalAlignment.Center sf.Alignment = StringAlignment.Center '//right Case HorizontalAlignment.Right sf.Alignment = StringAlignment.Far End Select '//advance X according to order If (bRightToLeft) Then '//draw the cell bounds (lines) and back color g.FillRectangle(New SolidBrush(PrintGrid.BackColor), CurrentX - PrintGrid.Cell(i, j).Width, CurrentY, PrintGrid.Cell(i, j).Width, PrintGrid.Cell(i, j).Height) g.DrawRectangle(New Pen(PrintGrid.LineColor), CurrentX - PrintGrid.Cell(i, j).Width, CurrentY, PrintGrid.Cell(i, j).Width, PrintGrid.Cell(i, j).Height) '//draw the cell text g.DrawString(PrintGrid.Cell(i, j).CText, PrintGrid.Cell(i, j).Font, New SolidBrush(PrintGrid.ForeColor), New RectangleF(CurrentX - PrintGrid.Cell(i, j).Width, CurrentY, PrintGrid.Cell(i, j).Width, PrintGrid.Cell(i, j).Height), sf) '//next cell CurrentX -= PrintGrid.Cell(i, j).Width Else '//draw the cell bounds (lines) and back color g.FillRectangle(New SolidBrush(PrintGrid.BackColor), CurrentX, CurrentY, PrintGrid.Cell(i, j).Width, PrintGrid.Cell(i, j).Height) g.DrawRectangle(New Pen(PrintGrid.LineColor), CurrentX, CurrentY, PrintGrid.Cell(i, j).Width, PrintGrid.Cell(i, j).Height) '//draw the cell text '//Draw text by alignment g.DrawString(PrintGrid.Cell(i, j).CText, PrintGrid.Cell(i, j).Font, New SolidBrush(PrintGrid.ForeColor), New RectangleF(CurrentX, CurrentY, PrintGrid.Cell(i, j).Width, PrintGrid.Cell(i, j).Height), sf) '//next cell CurrentX += PrintGrid.Cell(i, j).Width End If Next '//reset to beginning If (bRightToLeft) Then '//right align CurrentX = PrintDoc.DefaultPageSettings.PaperSize.Width - PrintDoc.DefaultPageSettings.Margins.Right Else '//left align CurrentX = PrintDoc.DefaultPageSettings.Margins.Left End If '//advance to next row CurrentY += PrintGrid.Cell(i, 0).Height CurrentRow += 1 '//if we are beyond the page margin (bottom) then we need another page, '//return true If (CurrentY > PrintDoc.DefaultPageSettings.PaperSize.Height - PrintDoc.DefaultPageSettings.Margins.Bottom) Then Return True End If Next Return False End Function End Class End Namespace

    Read the article

1 2 3  | Next Page >