Sometimes we need to know the width of a given string in pixels, do you know how to compute it? Before writing some long code, please notice that the .NET framework class library provides such a method. When Googling about this issue, we find the Graphics.MeasureString Method, here is how to use it:
Graphics graphics = this.CreateGraphics(); SizeF textSize = graphics.MeasureString("How long am I?", this.Font);
Nice isn’t it? Well, there is one little problem here, how is the Graphics object created? The written code is a Windows Forms code, so the this is the Form itself. You can’t create the Graphics object by simply allocating it because…
We have all used WPF DataTemplates, but I bet most of you never gave thought to the meaning of the x:Key attribute. We all know the meaning of the DataType attribute, which determines to what type of data the template will apply to. But what about the x:Key why is it there? Lets tale a look at the following code:
<Window.Resources> <DataTemplate DataType="{x:Type data:s}"> <Button Width="50" Height="50"> <TextBlock Text="{Binding text}"></TextBlock> </Button> </DataTemplate> </Window.Resources> <Canvas> <ItemsControl ItemsSource="{Binding}"> </ItemsControl> </Canvas>