我在 Canvas 内定义了一个 Grid >
< Canvas x:Name =outerCanvas> < Grid Grid.Row =1Name =cGridShowGridLines =TrueWidth ={Binding Path = ActualWidth,RelativeSource = {RelativeSource AncestorType = {x:Type Canvas}}}Height = {Binding Path = ActualHeight,RelativeSource = {RelativeSource AncestorType = {x:Type Canvas}}}> < Grid.ColumnDefinitions> < ColumnDefinition /> < ColumnDefinition /> < ColumnDefinition /> < /Grid.ColumnDefinitions> < Grid.RowDefinitions> < RowDefinition /> < RowDefinition /> < /Grid.RowDefinitions> < Rectangle Name =rectangle1Stroke =BlackFill =AntiqueWhite/>观察:
您可以在之前手动调用窗口的 Measure()和 Arrange()方法来强制计算这些值窗口的 InitializeComponent()返回。
如果您调整内容大小:
window.Measure(new Size(double.PositiveInfinity,double.PositiveInfinity)); window.Arrange(new Rect(0,0,window.DesiredSize.Width,window.DesiredSize.Height));如果您使用明确的窗口大小:
window.Measure(new Size(Width,Height)); window.Arrange(new Rect(0,0,window.DesiredSize.Width,window.DesiredSize.Height));
I have a Grid inside a Canvas defined like this:
<Canvas x:Name="outerCanvas"> <Grid Grid.Row="1" Name="cGrid" ShowGridLines="True" Width="{Binding Path=ActualWidth, RelativeSource={RelativeSource AncestorType={x:Type Canvas}}}" Height="{Binding Path=ActualHeight, RelativeSource={RelativeSource AncestorType={x:Type Canvas}}}"> <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition/> <ColumnDefinition/> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition /> <RowDefinition /> </Grid.RowDefinitions> <Rectangle Name="rectangle1" Stroke="Black" Fill="AntiqueWhite" /> <Rectangle Grid.Row="0" Grid.Column="1" Grid.ColumnSpan="1" Grid.RowSpan="1" Name="rectangle2" Stroke="Black" Fill="AliceBlue" /> <Rectangle Grid.Row="0" Grid.Column="2" Grid.ColumnSpan="1" Grid.RowSpan="1" Name="rectangle3" Stroke="Black" Fill="Aqua" /> <Rectangle Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="3" Grid.RowSpan="1" Name="rectangle4" Stroke="Black" Fill="DarkViolet" /> </Grid> </Canvas>My problem is that, on the Window constructor, after InitializeComponents() either Grid.ColumnDefinitions[0].ActualWidth or "any rectangle".ActualWidth are all set to 0.0 (the same for heights). I'm not figuring out what to do to get this information. Any help?
Observations:
解决方案
ActualHeight and ActualWidth are not set until the control is measured and arranged. Usually there is nothing in InitializeComponent() that causes a measure, so when it returns these will still be zero.
You can force these to be computed earlier by simply calling the window's Measure() and Arrange() methods manually after the window's InitializeComponent() returns.
If you are sizing to content:
window.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); window.Arrange(new Rect(0, 0, window.DesiredSize.Width, window.DesiredSize.Height));If you are using an explicit window size:
window.Measure(new Size(Width, Height)); window.Arrange(new Rect(0, 0, window.DesiredSize.Width, window.DesiredSize.Height));
更多推荐
为什么在这种情况下ActualWidth和ActualHeight 0.0?
发布评论