【发布时间】:2012-12-21 14:03:09
【问题描述】:
我想创建一个允许旋转其内容的按钮控件。我的课看起来像这样。 ApplyRotation 确实被调用,但文本保持水平。
我忘记了什么吗?使布局无效或类似的东西...
public class KeyButton : Button
{
private TextBlock content;
private Viewbox viewbox;
#region DEPENDENCY - Angle
// Dependency Property
public static readonly DependencyProperty AngleProperty =
DependencyProperty.Register("Angle", typeof(double),
typeof(KeyButton),
new FrameworkPropertyMetadata(0.0, OnAnglePropertyChanged, OnCoerceAngleProperty),
OnValidateAngleProperty);
// .NET Property wrapper
public double Angle
{
get { return (double)GetValue(AngleProperty); }
set { SetValue(AngleProperty, value); }
}
private static void OnAnglePropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e)
{
KeyButton control = source as KeyButton;
if (control != null)
{
ApplyRotation(control);
}
}
private static object OnCoerceAngleProperty(DependencyObject sender, object data)
{
// TODO implement
return data;
}
private static bool OnValidateAngleProperty(object data)
{
// TODO implement validation
return data is double;
}
#endregion
public KeyButton()
{
viewbox = new Viewbox();
content = new TextBlock { Text = "X" };
this.Content = viewbox;
viewbox.Child = content;
}
private static void ApplyRotation(KeyButton control)
{
if (control.viewbox.Child != null)
{
control.viewbox.Child.RenderTransform = new RotateTransform(control.Angle);
}
}
protected override void OnPropertyChanged(System.Windows.DependencyPropertyChangedEventArgs e)
{
base.OnPropertyChanged(e);
switch (e.Property.Name)
{
case "Content":
content.Text = e.NewValue.ToString();
ApplyRotation(this);
break;
default:
try
{
viewbox.SetValue(e.Property, e.NewValue);
}
catch (Exception)
{
}
break;
}
}
}
我使用 XAML 进行了尝试,它运行良好。 (我有大约 100 个按钮,所以我认为创建一个新类会更好......)
<Button Grid.Row="0" Grid.Column="0">
<Viewbox>
<TextBlock Text="Hello">
<TextBlock.RenderTransform>
<RotateTransform Angle="45"/>
</TextBlock.RenderTransform>
</TextBlock>
</Viewbox>
</Button>
【问题讨论】:
-
所有 Button 的 Rotation 是否不同,还是在运行时发生变化?
-
我只对一个按钮应用了一个角度,它没有效果。 set 属性方法仅以新角度(45°)调用一次,但文本保持水平...
标签: wpf rotatetransform