代码隐藏弹出窗口ActualHeight和ActualWidth始终为0

时间:2015-03-27 18:32:45

标签: c# .net wpf xaml

我正在创建一个代码隐藏弹出窗口。在按钮上单击添加子项并设置IsOpen = true。现在我可以看到弹出窗口。 我有另一个按钮,点击,弹出窗口的ActualHeight(和ActualWidth)总是返回0.我怎样才能获得实际值? 注意:Snoop显示正确的值。

代码段:

public partial class MainWindow : Window
{
    private Popup popup = new Popup();

    public MainWindow()
    {
        InitializeComponent();
    }

    private void ButtonShowPopup_OnClick(object sender, RoutedEventArgs e1)
    {
        var dockPanel = new DockPanel();
        dockPanel.Children.Add(new TextBlock { Text = "First TextBlock", Background = Brushes.White });
        popup.Child = dockPanel;
        popup.IsOpen = true;
    }

    private void ButtonProperties_OnClick(object sender, RoutedEventArgs e)
    {
        Dispatcher.BeginInvoke(DispatcherPriority.Background, new DispatcherOperationCallback(delegate(Object state)
        {
            MessageBox.Show(popup.ActualHeight.ToString());
            return null;
        }), null);
        MessageBox.Show(popup.ActualHeight.ToString());
    }
}

的Xaml:

 <Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition></ColumnDefinition>
        <ColumnDefinition></ColumnDefinition>
    </Grid.ColumnDefinitions>
    <Button Grid.Column="0" Click="ButtonShowPopup_OnClick" Content="ShowPopup"></Button>
    <Button Grid.Column="1" Click="ButtonProperties_OnClick"  Content="Get Actual height &amp; Width"></Button>
</Grid>

1 个答案:

答案 0 :(得分:1)

使用Popup.Child对象。

...
private void ButtonProperties_OnClick(object sender, RoutedEventArgs e)
{
    MessageBox.Show(popup.Child.RenderSize.Height.ToString(CultureInfo.InvariantCulture));
}
...