none
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; }
                set
                {
                    _Di = value;
                    NotifyPropertyChanged();
                }
            }

    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

Answers

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

    Give TB2 a name in the XAML markup:

    <UserControl x:Class="WpfApplication1.TB2"
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
                 xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
                 xmlns:local="clr-namespace:WpfApplication22"
                 mc:Ignorable="d" 
                 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