【问题标题】:Line is not displayed on startup but becomes visible on resize (WPF)线在启动时不显示,但在调整大小时可见(WPF)
【发布时间】:2014-06-26 19:18:33
【问题描述】:

我有一个 WPF 应用程序,其中仅在调整应用程序窗口大小时才显示线条形状,如下所示:

红线是即时绘制的,它没有在 XAML 中定义。显示正常。

蓝线是在 XAML 中定义的,但它的尺寸在 OnRender() 调用中发生了变化。如果其尺寸未更改,或者仅更改了 部分 尺寸,则会在启动时显示蓝线。但是当all蓝线的尺寸发生变化时,它在启动时显示。它仅在应用程序调整大小时显示。

这是 XAML 代码:

<Window x:Class="canvas_line.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:canvas_line" 
        Title="MainWindow" Height="284" Width="228">
    <Canvas Name="canvas">
        <local:show_line />
        <Line Name="my_line" Stroke="Blue" 
            X1="50" Y1="40" X2="50" Y2="80" StrokeThickness="4" />
    </Canvas>
</Window>

还有 C# 代码隐藏文件:

using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Linq;

namespace canvas_line
{
    public partial class show_line: FrameworkElement
    {
        protected override void OnRender(DrawingContext dc)
        {
            base.OnRender(dc);              // Good practice.

            // Draw a brand-new red line defined here only 
            // (not defined in XAML).

            Pen dp = new Pen(Brushes.Red, 4);
            dc.DrawLine(dp, new Point(100, 150), new Point(100, 200));

            // Now modify coordinates of the blue line defined in XAML.

            Canvas cp = (Canvas)this.Parent;
            var my_line = cp.Children.OfType<Line>().FirstOrDefault();
            my_line.X1 = 100;
            my_line.Y1 = 20;
            my_line.X2 = 100;
            my_line.Y2 = 50;

            // Problem: The blue line is not displayed unless
            // the application window is resized.
        }
    }
}

整个项目的 zip 文件在这里(项目中的代码很少,我已将其修剪到演示问题所需的绝对最低限度):

https://anonfiles.com/file/18c6edce296927b43ed0b0d595574a80

我尝试了对UpdateLayout()InvalidateVisual() 的各种调用组合,但均无效。为什么会发生这种情况,是否有解决方法?我的最终目标是能够为蓝线设置动画以使其闪烁。

我使用的是 Windows 7、Visual Studio 10、.NET 4.0 客户端配置文件。

【问题讨论】:

  • PS:我需要调用OnRender(),因为虽然这里没有显示,但我必须进行低级字形绘制。谢谢。
  • 您是否尝试过在 base.OnRender 之前更改位置?
  • @JohnKoerner 是的,不起作用。
  • 我怀疑您正在清除 base.OnRender() 中的绘图上下文。你能发布那个代码吗?或者,您可以检查删除 base.OnRender() 是否会恢复蓝线。
  • @TylerKendrick 我删除了base.OnRender(),没什么区别。

标签: c# wpf frameworkelement drawingcontext onrender


【解决方案1】:

如果你这样写它会正确绘制

 <Canvas Name="canvas">
    <Line Name="my_line" Stroke="Blue" X1="50" Y1="40" X2="50" Y2="80" StrokeThickness="4" />
    <local:show_line />
 </Canvas>  

【讨论】:

  • 工作,谢谢!为什么是这样?你以前见过这种行为吗,你是怎么想出解决办法的?
  • @Henna Patil:+1 好收获。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-04-22
  • 1970-01-01
  • 1970-01-01
  • 2016-01-14
  • 2016-01-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多