我正在尝试使用 7 段显示器创建数字时钟显示器。我可以使用如下代码在 XAML 中绘制线条:
<Line Name="line7" Stroke="Black" StrokeThickness="4" X1="10" X2="40" Y1="70" Y2="70" Margin="101,-11,362,250" />
但是当我尝试在代码中执行此操作(来自 MainWindow())时,它不起作用:
Line line = new Line();
Thickness thickness = new Thickness(101,-11,362,250);
line.Margin = thickness;
line.Visibility = System.Windows.Visibility.Visible;
line.StrokeThickness = 4;
line.Stroke = System.Windows.Media.Brushes.Black;
line.X1 = 10;
line.X2 = 40;
line.Y1 = 70;
line.Y2 = 70;
这个想法是我可以画 7 条线,然后根据需要为不同的数字切换它们的可见性。我相信这可以通过多种方式完成,但是为什么我不能像这样在代码中画线呢?
这是你的整个绘图代码吗?如果是这样,则需要将line
对象添加到曲面。例如,如果您使用的是全屏广告:
myCanvas.Children.Add(line);
这会将您的线条添加到画布中。目前,您只是在创建线条,而不是将其放在任何地方。
您可以在此 MSDN 页面上找到有关在 WPF 中绘制的详细信息。
public class Cls_Barriere
{
// animazione periferica
public static void LineAnimation(Line _line,String _colore)
{
Storyboard result = new Storyboard();
Duration duration = new Duration(TimeSpan.FromSeconds(2));
ColorAnimation animation = new ColorAnimation();
animation.RepeatBehavior = RepeatBehavior.Forever;
animation.Duration = duration;
switch (_colore.ToUpper())
{
case "RED":
animation.From = Colors.Red;
break;
case "ORANGE":
animation.From = Colors.Orange;
break;
case "YELLOW":
animation.From = Colors.Yellow;
break;
case "GRAY":
animation.From = Colors.DarkGray;
break;
default:
animation.From = Colors.Green;
break;
}
animation.To = Colors.Gray;
Storyboard.SetTarget(animation, _line);
Storyboard.SetTargetProperty(animation, new PropertyPath("(Line.Stroke).(SolidColorBrush.Color)"));
result.Children.Add(animation);
result.Begin();
}
}
//***************************************************************************
public partial class MainPage : UserControl
{
public Line _line;
public MainPage()
{
InitializeComponent();
Canvas.MouseLeftButtonDown += Canvas_MouseLeftButtonDown;
Canvas.MouseLeftButtonUp += Canvas_MouseLeftButtonUp;
}
void Canvas_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
_line.X2 = e.GetPosition(this.Canvas).X;
_line.Y2 = e.GetPosition(this.Canvas).Y;
_line.Loaded += _line_Loaded;
Canvas.Children.Add(_line);
}
void _line_Loaded(object sender, RoutedEventArgs e)
{
Cls_Barriere.LineAnimation(sender as Line, "RED");
}
void Canvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
_line = new Line();
_line.Stroke = new SolidColorBrush(Colors.White);
_line.StrokeThickness = 5;
_line.StrokeStartLineCap = PenLineCap.Round;
_line.StrokeEndLineCap = PenLineCap.Round;
_line.StrokeDashCap = PenLineCap.Round;
_line.X1 = e.GetPosition(this.Canvas).X;
_line.Y1= e.GetPosition(this.Canvas).Y;
}