WPF依赖属性改变ActualWidth == 0



我如何强制一个窗口在构造函数中测量其控件,使ActualWidthActualHeight的值不为零?以下是演示我的问题的示例(我试图调用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从左边缘到右边缘的竖线数。当我改变文本框中的值时,它工作得很好,但是我希望线条已经在开始绘制了。

那么我需要如何更新代码,以便在开始时已经绘制线条,请?或者,与上述代码不同的方法是否更适合实现这一目标?

谢谢你的努力

也许你可以把逻辑放在OnContentRendered

Windows Content应该全部布局,ActualWidth等应该准备好了。

的例子:

protected override void OnContentRendered(EventArgs e)
{
    base.OnContentRendered(e);
    // Logic
}

最新更新