如何强制 Window 在构造函数中测量其控件,以便 和 的值ActualWidth
不ActualHeight
为零?这是演示我的问题的示例(我尝试调用 Measure 和 Arrange 函数,但可能以错误的方式)。
XAML:
<Window x:Class="WpfApplication7.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
WindowStartupLocation="CenterScreen"
Title="WPF Diagram Designer"
Background="#303030"
Height="600" Width="880" x:Name="Root">
<Grid x:Name="LayoutRoot">
<DockPanel>
<TextBox DockPanel.Dock="Top" Text="{Binding ElementName=Root, Mode=TwoWay, Path=Count}"/>
<Button DockPanel.Dock="Top" Content="XXX"/>
<Canvas x:Name="MainCanvas">
</Canvas>
</DockPanel>
</Grid>
</Window>
后面的代码:
using System.Windows;
using System.Windows.Controls;
using System.Windows.Shapes;
using System;
using System.Windows.Media;
namespace WpfApplication7
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));
Arrange(new Rect(DesiredSize));
Count = 6;
}
public static readonly DependencyProperty CountProperty = DependencyProperty.Register("Count",
typeof(int), typeof(Window1), new FrameworkPropertyMetadata(5, CountChanged, CoerceCount));
private static object CoerceCount(DependencyObject d, object baseValue)
{
if ((int)baseValue < 2) baseValue = 2;
return baseValue;
}
public int Count
{
get { return (int)GetValue(CountProperty); }
set { SetValue(CountProperty, value); }
}
private static void CountChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
Window1 w = d as Window1;
if (w == null) return;
Canvas c = w.MainCanvas;
if (c == null || c.Children == null) return;
c.Children.Clear();
if (c.ActualWidth == 0) MessageBox.Show("XXX");
for (int i = 0; i < w.Count; i++)
c.Children.Add(new Line()
{
X1 = c.ActualWidth * i / (w.Count - 1),
X2 = c.ActualWidth * i / (w.Count - 1),
Y1 = 0,
Y2 = c.ActualHeight,
Stroke = Brushes.Red,
StrokeThickness = 2.0
});
}
}
}
这个例子的重点是从左边缘到右边缘绘制了Count条垂直线。当我更改 TextBox 中的值时效果很好,但是我希望已经在开始时绘制线条。
那么我需要如何更新代码以在开始时绘制线条呢?还是与上述代码不同的方法更适合实现这一目标?
感谢您的任何努力。