I'd like to draw a big number on a Canvas, wrapped in a rectangle, but I don't know how to do that. My idea is to create a style and then to apply it to some Label instance which changes its size:
<Style x:Key="CountdownLabel" TargetType="Label">
<Setter Property="FontFamily" Value="Arial"></Setter>
<Setter Property="Foreground" Value="Navy"></Setter>
<Setter Property="FontWeight" Value="Bold"></Setter>
<Setter Property="FontSize" Value="40"></Setter>
<Setter Property="FontStretch" Value="UltraExpanded"></Setter>
<Set开发者_开发百科ter Property="Control.Template">
<Setter.Value>
<ControlTemplate>
<Border>
<Rectangle Margin="0,0,0,0" Stroke="#60000000" StrokeThickness="1" StrokeDashArray="1 2" />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
I set label.Content=number.ToString()
in code-behind but the number is not showed. Also, I wouldn't know how to resize the label for filling the Canvas parent.
Regards.
There are two things you need to correct in your template:
- You don't include a ContentPresenter, so there's nothing to tell the layout system "oh, by the way, here's where you should insert what's in the Label's Content property".
- You need to specify TargetType on your ControlTemplate. (Just one of those things you learn to try when templates aren't working.)
Here's an adjusted version that works. I changed your Border to a Grid so it could accommodate two child controls (the Rectangle for the dashed border, and a ContentPresenter to show the Content). I stole the ContentPresenter declaration from an example on MSDN; it may not be complete, but it should get you started.
<Style x:Key="CountdownLabel" TargetType="Label">
<Setter Property="FontFamily" Value="Arial"/>
<Setter Property="Foreground" Value="Navy"/>
<Setter Property="FontWeight" Value="Bold"/>
<Setter Property="FontSize" Value="40"/>
<Setter Property="FontStretch" Value="UltraExpanded"/>
<Setter Property="Control.Template">
<Setter.Value>
<ControlTemplate TargetType="Label">
<Grid>
<Rectangle Margin="0,0,0,0" Stroke="#60000000" StrokeThickness="1"
StrokeDashArray="1 2" MinWidth="10" MinHeight="10"/>
<ContentPresenter
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
RecognizesAccessKey="True" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
精彩评论