Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find UserControl width in WPF?

<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>

This is my UserControl and i have not set its Width and Height properties. But in some codebehind i want to get the Height and width of this UserControl and i am not able to get them.

double width=uctrl.Width;

It gives me NaN while

double width=ctrl.ActualWidth;

giving me 0

The code where i need width and height

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);
    }
}
like image 722
Kishore Kumar Avatar asked Nov 05 '22 01:11

Kishore Kumar


1 Answers

In a brand new project I wrote this (and it gave me updated width when changing the Window):

<Window xmlns:my="clr-namespace:WpfApplication2"
        x:Class="WpfApplication2.Window32"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window32"
        Height="300"
        Width="300">
  <Grid>
    <my:UserControl3 x:Name="uc3" />
    <TextBlock Height="23"
               HorizontalAlignment="Left"
               Margin="126,121,0,0"
               Name="textBlock1"
               Text="{Binding ElementName=uc3, Path=ActualWidth}"
               VerticalAlignment="Top" />
  </Grid>
</Window>
like image 66
NestorArturo Avatar answered Nov 09 '22 10:11

NestorArturo