WPF依赖项属性已更改实际宽度== 0

时间:2013-05-05 22:15:06

标签: wpf wpf-controls dependency-properties actualwidth actualheight

如何强制窗口在构造函数中测量其控件,以使ActualWidthActualHeight的值不为零?以下是演示我的问题的示例(我试图调用测量和排列函数,但可能是错误的方式)。

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中的值时,它运行良好,但我希望在开头绘制线条。

那么我如何才能更新代码以便在开头绘制线条了?或者,与上述代码不同的方法是否更适合实现这一目标?

感谢您的任何努力。

1 个答案:

答案 0 :(得分:1)

也许您可以将逻辑放在OnContentRendered

Windows Content应该全部布局,ActualWidth等应该准备就绪。

示例:

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

    // Logic
}