1

如何強制窗口在構造函數中測量其控件,以使ActualWidthActualHeight的值不爲零?這裏是展示我的問題的示例(我嘗試調用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中的值時,它工作的很好,但是我想要在開始時繪製線條。

那麼我該如何更新代碼才能在開頭畫線?或者,爲了達到這個目標,會採用與上述代碼不同的方法嗎?

謝謝你的努力。

+1

也許你可以把邏輯'保護覆蓋無效OnContentRendered(EventArgs的)',在Windows的內容應該是所有奠定了那時和ActualWith等應該準備好。 – 2013-05-05 22:18:37

+0

這回答了我的問題,非常感謝。請將其寫入答案,以便我可以將此問題標記爲已回答,謝謝。 – 2013-05-05 22:22:11

回答

1

也許你可以把邏輯放在OnContentRendered

Windows Content應該是所有佈局,然後ActualWidth等應準備好。

例子:

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

    // Logic 
}