在WPF中从控件内部查找控件的宽度

时间:2014-10-15 07:07:24

标签: c# wpf xaml user-controls

我有一个用户控件需要根据控件的总宽度设置其中一个变量。

<UserControl x:Class="MyControl"
   ...
    x:Name="MyControlRoot">
    <Grid DataContext="{Binding ElementName=MyControlRoot}">
        <Canvas>
            <Ellipse Width="{Binding MyWidth}" Height="{Binding MyHeight}" 

在后面的代码中,属性定义如下:

    public double MyWidth
    {
        get
        {
            return (ActualWidth - 5);
        }
    }

我尝试了ActualWidthWidth,甚至尝试访问根元素的宽度,但似乎无法在运行时确定控件的宽度;我得到0或NaN。

我的问题是:如何从控件中访问运行时的宽度?

1 个答案:

答案 0 :(得分:1)

也许试试这个

Width="{Binding RelativeSource={RelativeSource AncestorType=UserControl}, Path=ActualWidth}"