ActualWidth
およびの値がActualHeight
ゼロにならないように、ウィンドウにコンストラクター内のコントロールを強制的に測定させるにはどうすればよいですか? これが私の問題を示すサンプルです(メジャー関数とアレンジ関数を呼び出そうとしましたが、間違った方法である可能性があります)。
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 の値を変更するとうまくいきますが、最初に線を描画したいです。
では、最初に線を描画するようにコードを更新するにはどうすればよいですか? または、この目標を達成するには、前述のコードとは異なるアプローチがより適切でしょうか?
ご尽力いただきありがとうございます。