设定一个用户控件NumberTextBox,其中包含Label和TextBox:
<Stackpanel Ori…>
<Label Content = “{Binding ElementName = root, Path=Label}”/>
<TextBox Width=”{Binding ElementName = root,Path=TextWidth}”/>
</Stackpanel>.cs文件中加入两个以来属性,分别为Label和TextWidth,其形式为:#region TextWidth
public static readonly DependencyProperty TextWidthProperty = DependencyProperty.Register(
            "TextWidth", typeof(Double), typeof(NumberTextBox));        public Double TextWidth
        {
            get { return (Double)GetValue(TextWidthProperty); }
            set { SetValue(TextWidthProperty, value); }
        }
#endregion
Label为string类型
调用形式为<local:NumberTextBox TextWidth=”100” Label=”hello”></…>
但是该绑定就没有成功过,不知道为什么?

解决方案 »

  1.   

    local:NumberTextBox 没有x:Name?
    或者<NumberTextBox>定义位置有问题?我仿照你提供的信息写了一个概括,没有任何问题的,不是上述问题那把代码贴出来讨论一下吧    <StackPanel>
            <local:NumberTextBox x:Name="root" TextWidth="100" Label="hello"></local:NumberTextBox>
            <Label Content ="{Binding ElementName = root, Path=Label}"/>
            <TextBox Width="{Binding ElementName = root,Path=TextWidth}"/>
        </StackPanel>    public class NumberTextBox : Control
        {
            public static readonly DependencyProperty TextWidthProperty = DependencyProperty.Register("TextWidth", typeof(Double), typeof(NumberTextBox));
            public static readonly DependencyProperty LabelProperty = DependencyProperty.Register("Label", typeof(string), typeof(NumberTextBox));        public Double TextWidth
            {
                get { return (Double)GetValue(TextWidthProperty); }
                set { SetValue(TextWidthProperty, value); }
            }
            public string Label
            {
                get { return (string)GetValue(LabelProperty); }
                set { SetValue(LabelProperty, value); }
            }
        }
      

  2.   

    我其实是想定义一个用户控件NumberTextBox,用户控件中有一个Label和TextBox,如果我指定Label属性,就是给Label赋值,如果制定TextWidth,就是给TextBox的Width赋值。也就是说,Label和textBox都是用户控件的一个属性元素。您可能误解了我的意思。不过还是谢谢了!
      

  3.   

    我其实是想定义一个用户控件NumberTextBox,用户控件中有一个Label和TextBox,如果我指定Label属性,就是给Label赋值,如果制定TextWidth,就是给TextBox的Width赋值。也就是说,Label和textBox都是用户控件的一个属性元素。您可能误解了我的意思。不过还是谢谢了!