如何在 WPF 中找到 UserControl 宽度?

Kis*_*mar 5 c# wpf user-controls

<UserControl x:Class="JIMS.View.Settings.Settings"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
    Name="SettingsWindow">       
    <Border Style="{StaticResource WindowBorderStyle}" Height="100">    
    <StackPanel Orientation="Vertical">
        <my:TitleBar Title="settings"/>
        <StackPanel Orientation="Horizontal">
            <StackPanel Orientation="Horizontal">
                <StackPanel Orientation="Vertical" Margin="10,0,0,0">
                    <Label>Theme :</Label>                        
                </StackPanel>
                <StackPanel Orientation="Vertical" Width="200" Margin="0,0,10,0">                        
                    <ComboBox Name="cmbTheme" ItemsSource="{Binding Path=Themes}" ></ComboBox>                        
                </StackPanel>
            </StackPanel>
        </StackPanel>
    </StackPanel>        
</Border>
</UserControl>
Run Code Online (Sandbox Code Playgroud)

这是我的 UserControl,我还没有设置它的 Width 和 Height 属性。但是在某些代码隐藏中,我想获得此 UserControl 的高度和宽度,但我无法获得它们。

double width=uctrl.Width;
Run Code Online (Sandbox Code Playgroud)

它让我NaN同时

double width=ctrl.ActualWidth;
Run Code Online (Sandbox Code Playgroud)

给我 0

我需要宽度和高度的代码

private void OpenChild(UserControl ctrl)
{
    bool alreadyExist = false;
    ctrl.Uid = ctrl.Name;
    foreach (UIElement child in JIMSCanvas.Children)
    {
        if (child.Uid == ctrl.Uid)
        {
            alreadyExist = true;
            Canvas.SetZIndex(child, GetMaxZIndex);
        }
    }
    if (!alreadyExist)
    {
        JIMSCanvas.Children.Add(ctrl);
            JIMSCanvas.InvalidateMeasure();
        double top = (JIMSCanvas.ActualHeight - ctrl.Height) / 2;
        double left = (JIMSCanvas.ActualWidth - ctrl.Width) / 2;
        Canvas.SetLeft(ctrl, left);
        Canvas.SetTop(ctrl, top);
    }
}
Run Code Online (Sandbox Code Playgroud)

Kis*_*mar 0

我用这段代码解决了这个问题...

private void OpenChild(UserControl ctrl)
{
    bool alreadyExist = false;
    ctrl.Uid = ctrl.Name;
    foreach (UIElement child in JIMSCanvas.Children)
    {
        if (child.Uid == ctrl.Uid)
        {
            alreadyExist = true;
            Canvas.SetZIndex(child, GetMaxZIndex);
        }
    }
    if (!alreadyExist)
    {
        JIMSCanvas.Children.Add(ctrl);
        JIMSCanvas.UpdateLayout();
        double top = (JIMSCanvas.ActualHeight - ctrl.ActualHeight) / 2;
        double left = (JIMSCanvas.ActualWidth - ctrl.ActualWidth) / 2;
        Canvas.SetLeft(ctrl, left);
        Canvas.SetTop(ctrl, top);                               
    }
}
Run Code Online (Sandbox Code Playgroud)

我用过JIMSCanvas.UpdateLayout();

感谢大家的帮助,特别是@NestorArturo