更改WPF依赖项属性ActualWidth == 0
问题描述:
如何强制窗口在构造函数中测量其控件,以使ActualWidth
和ActualHeight
的值不为零?这里是展示我的问题的示例(我尝试调用Measure和Arrange函数,但可能以错误的方式)。更改WPF依赖项属性ActualWidth == 0
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
});
}
}
}
本实施例的点是,抽到计数数目的垂直线从左侧边缘至右侧边缘。当我改变TextBox中的值时,它工作的很好,但是我想要在开始时绘制线条。
那么我该如何更新代码才能在开头画线?或者,为了达到这个目标,会采用与上述代码不同的方法吗?
谢谢你的努力。
答
也许你可以把逻辑放在OnContentRendered
。
Windows Content
应该是所有布局,然后ActualWidth
等应准备好。
例子:
protected override void OnContentRendered(EventArgs e)
{
base.OnContentRendered(e);
// Logic
}
也许你可以把逻辑'保护覆盖无效OnContentRendered(EventArgs的)',在Windows的内容应该是所有奠定了那时和ActualWith等应该准备好。 – 2013-05-05 22:18:37
这回答了我的问题,非常感谢。请将其写入答案,以便我可以将此问题标记为已回答,谢谢。 – 2013-05-05 22:22:11