我需要向画布添加几个用户控件。 UserControl的大小取决于ItemsControlUserControl中存在的项目数。为了正确放置控件并在用户控件之间绘制互连线,我需要使用父画布的绝对宽度/高度。如何获得这些? ActualHeightActualWidth返回0。

我之前曾问过similar question,但没有得到正确的答案。

编辑:添加XAML od UserControl

<UserControl x:Class="SilverlightApplication2.MyControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
DataContext="{Binding RelativeSource={RelativeSource Self}}" Loaded="UserControl_Loaded">

<Grid x:Name="LayoutRoot" Background="White">
    <Border CornerRadius="3" BorderThickness="1" BorderBrush="LightGray">
        <Grid  Name="grid1" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" >
            <Grid.RowDefinitions>
                <RowDefinition Height="40*" />
                <RowDefinition Height="136*" />
            </Grid.RowDefinitions>
            ...
            <Grid Name="gridPC" Grid.Row="1">
                <Grid.RowDefinitions>
                    <RowDefinition Height="55*" />
                    <RowDefinition Height="*" />
                    <RowDefinition Height="55*" />
                    <RowDefinition Height="*" />
                </Grid.RowDefinitions>
                ....

                <ItemsControl x:Name="pitems" ItemsSource="{Binding RowsP}" Grid.Row="1">
                    <ItemsControl.ItemTemplate>
                        <DataTemplate>
                            <StackPanel Width="250" Orientation="Horizontal">
                                <TextBlock Text="{Binding X}" Width="100" />
                                <TextBlock Text="{Binding Y}" Width="130" />
                            </StackPanel>
                        </DataTemplate>
                    </ItemsControl.ItemTemplate>
                </ItemsControl>

               ......
            </Grid>
        </Grid>
    </Border>
</Grid>

最佳答案

您可以执行此操作的选项很少,强制调用Window.MeasureWindow.Arrange将计算所有值,或者您可以在Window.Loaded事件中获取这些值。已经在on this question中讨论了相同的问题。

如果要调整内容的大小:

window.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
window.Arrange(new Rect(0, 0, window.DesiredWidth, window.DesiredHeight));


如果使用显式窗口大小:

window.Measure(new Size(Width, Height));
window.Arrange(new Rect(0, 0, window.DesiredWidth, window.DesiredHeight));


要么

public MyWindow()
{
    Loaded += delegate
    {
        // access ActualWidth and ActualHeight here
    };

}

关于c# - 获取 Canvas 中UserControl的渲染大小,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8660861/

10-17 01:08