c# - 以编程方式获取当前列的宽度和高度?

标签 c# wpf xaml grid

我正在尝试在用户控件中以编程方式获取网格的宽度和高度。

这是我的 XAML 网格:

<Grid Name="BallGrid" Background="DarkBlue" Height="auto" Width="auto">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
</Grid>

但这两个:

double width = BallGrid.ColumnDefinitions[0].ActualWidth;
double height = BallGrid.RowDefinitions[0].ActualHeight;

返回0,

还有这些

double width = BallGrid.ColumnDefinitions[0].Width.Value;
double height = BallGrid.RowDefinitions[0].Height.Value;

返回都返回1。

我想知道实际宽度,最好采用与边距大小相同的单位。如何以编程方式获取这些值?

列值在 ProgessChanged 方法中查询,该方法由 BackgroundWorker 每 50 毫秒调用一次,也许这会有所不同。

最佳答案

通常你使用ActualWidth/Height,这里这些属性有点懒:

When you add or remove rows or columns, the ActualWidth for all ColumnDefinition elements and the ActualHeight of all RowDefinition elements becomes zero until Measure is called.

因此您可以手动调用 Measure 或尝试等待。

关于c# - 以编程方式获取当前列的宽度和高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12200838/

相关文章:

c# - 直接在 XAML 中绑定(bind)基于 SolidColorBrush 的设置

c# - Wpf 绑定(bind) Observablecollection 和 RelayCommand

c# - DataGridTextColumn 百分比宽度

xaml - 根据数据绑定(bind)值设置背景颜色

c# - 在azure sdk Fluent中使用身份验证 token

c# - 如何解决 TransactionScope 连接绑定(bind)不像 MSDN 所说的那样工作的事实?

c# - 为什么这个程序在 Release build 中进入 if block ,而在 Debug build 中不进入?

c# - “Column count doesn' t 第 1 行的匹配值计数”

wpf - 添加自定义触发器时如何保留 mahapps 地铁样式?

c# - 在 MVVM 模式中单击时更改按钮颜色