先展示一下控件效果:
这个控件在Windows Phone官方demo的PeopleHub里面貌似很常用,能显示好友在社交网站上的更新数量之类的,很符合Windows Phone的Metro设计风格,而且做起来也不难,用Path搞定外观,再想办法动态处理一下Text的大小就行了。懒惰起见我就用UserControl做了。
一、准备好UserControl,并编写xaml:
<Grid x:Name="LayoutRoot" Height="100" Width="100" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="80"/>
<RowDefinition Height="20"/>
</Grid.RowDefinitions>
<Path Fill="{StaticResource PhoneAccentBrush}" Grid.Row="0" Grid.RowSpan="2">
<Path.Data>
<PathGeometry>
<PathFigure StartPoint="0,0" IsClosed="True">
<LineSegment Point="100,0"></LineSegment>
<LineSegment Point="100,80"></LineSegment>
<LineSegment Point="40,80"></LineSegment>
<LineSegment Point="20,100"></LineSegment>
<LineSegment Point="20,80"></LineSegment>
<LineSegment Point="0,80"></LineSegment>
</PathFigure>
</PathGeometry>
</Path.Data>
</Path>
<TextBlock Name="tb" Grid.Row="0" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Grid>
<Grid.RowDefinitions>
<RowDefinition Height="80"/>
<RowDefinition Height="20"/>
</Grid.RowDefinitions>
<Path Fill="{StaticResource PhoneAccentBrush}" Grid.Row="0" Grid.RowSpan="2">
<Path.Data>
<PathGeometry>
<PathFigure StartPoint="0,0" IsClosed="True">
<LineSegment Point="100,0"></LineSegment>
<LineSegment Point="100,80"></LineSegment>
<LineSegment Point="40,80"></LineSegment>
<LineSegment Point="20,100"></LineSegment>
<LineSegment Point="20,80"></LineSegment>
<LineSegment Point="0,80"></LineSegment>
</PathFigure>
</PathGeometry>
</Path.Data>
</Path>
<TextBlock Name="tb" Grid.Row="0" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Grid>
二、定义一个依赖属性,以便设置提示板上面的数字:
public static readonly DependencyProperty NumProperty = DependencyProperty.Register("Num", typeof(int), typeof(NumPad), null);
三、在设置Num属性时根据数字大小动态设置FontSize,以便让其能显示得下:
if (value != Num)
{
tb.FontSize = FontSize;
tb.Text = value.ToString();
if (tb.ActualWidth > LayoutRoot.ActualWidth * 0.9 && LayoutRoot.ActualWidth > 0.0)
{
tb.FontSize = FontSize * (LayoutRoot.Width / tb.ActualWidth * 0.8);
}
SetValue(NumProperty, value);
}
{
tb.FontSize = FontSize;
tb.Text = value.ToString();
if (tb.ActualWidth > LayoutRoot.ActualWidth * 0.9 && LayoutRoot.ActualWidth > 0.0)
{
tb.FontSize = FontSize * (LayoutRoot.Width / tb.ActualWidth * 0.8);
}
SetValue(NumProperty, value);
}
四、其他处理,很简单了:
private void NumPad_Loaded(object sender, RoutedEventArgs args)
{
tb.FontSize = FontSize;
tb.Text = Num.ToString();
if (tb.ActualWidth > LayoutRoot.ActualWidth * 0.9 && LayoutRoot.ActualWidth > 0.0)
{
tb.FontSize = FontSize * (LayoutRoot.Width / tb.ActualWidth * 0.8);
}
}
{
tb.FontSize = FontSize;
tb.Text = Num.ToString();
if (tb.ActualWidth > LayoutRoot.ActualWidth * 0.9 && LayoutRoot.ActualWidth > 0.0)
{
tb.FontSize = FontSize * (LayoutRoot.Width / tb.ActualWidth * 0.8);
}
}
五、使用方法:
<controls:NumPad x:Name="np" FontSize="40" Foreground="Yellow"/>
至此大功告成。其实就是个带形状的TextBlock。
» 转载请注明来源及链接:未来代码研究所