Binding of a dependency property in a userControl does't work! RRS feed

  • Question

  •         public static readonly DependencyProperty myTBProperty =
                DependencyProperty.Register("myTB", typeof(decimal?), typeof(TB2), new FrameworkPropertyMetadata() { BindsTwoWayByDefault = true });
            public decimal? myTB
                get { return (decimal?)GetValue(myTBProperty); }
                set { SetValue(myTBProperty, value); }
            <TextBox Grid.Column="1" Text="{Binding myTB,Mode=TwoWay}" Width="{Binding TBWidth}"/>

    The above code is for a UserControl. 

    Now I used this UserControl into another UserControl like this:

         <c:TB2 myText="OutSide Diameter" myTB="{Binding Di,Mode=TwoWay}" TBWidth="120"/>
            private decimal? _Di;
            public decimal? Di
                get { return _Di; }
                    _Di = value;

    But when I change the Value of Di, nothing happens. I have also tried with an ordinary TextBox and it works. 

    Wednesday, February 4, 2015 11:37 AM


  • You cannot explicitly set the DataContext of the TB2 UserControl.

    Give TB2 a name in the XAML markup:

    <UserControl x:Class="WpfApplication1.TB2"
                 d:DesignHeight="300" d:DesignWidth="300" Name="tb2">

    ...and bind to the myTB property of the UC using the ElementName syntax:

            <TextBox Grid.Column="1" Text="{Binding myTB,Mode=TwoWay, ElementName=tb2}" Width="{Binding TBWidth}"/>

    Do not set the DataContext of TB2 to itself programmatically because then you cannot bind to the Di source property in the other UC.

    Please remember to close your threads by marking helpful posts as answer and please upload a reproducable sample of your issue to OneDrive and post the link to it here if you need any further help. It is impossible for anyone but you to know what is going on behind the scenes in your application.

    Wednesday, February 4, 2015 12:11 PM