gpt4 book ai didi

c# - 获取 Canvas 中 UserControl 的渲染大小

转载 作者:太空宇宙 更新时间:2023-11-03 20:28:56 25 4
gpt4 key购买 nike

我需要向 Canvas 添加多个用户控件。 UserControl 的大小取决于 UserControlItemsControl 中存在的项目数。要正确定位控件并在用户控件之间绘制互连线,我需要相对于父 Canvas 的绝对宽度/高度。如何获得这些? 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com