ali ali - 17 days ago 8
C# Question

error on accessing a property of a control in a wpf user control

i have created a wpf user control with a text box and a combo box.
for accessing the text property of the text box i have used the below code

public static readonly DependencyProperty TextBoxTextP = DependencyProperty.Register(
"TextBoxText", typeof(string), typeof(TextBoxUnitConvertor));

public string TextBoxText
{
get { return txtValue.Text; }
set { txtValue.Text = value; }
}


in another project i have used the control and bind the text as below:

<textboxunitconvertor:TextBoxUnitConvertor Name="wDValueControl" TextBoxText="{Binding _FlClass.SWa_SC.Value , RelativeSource={RelativeSource AncestorType=Window}, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" Width="161" Height="28" HorizontalAlignment="Left" VerticalAlignment="Top"/>


i am certain that the class that is used for binding is properly working because when i used it to bing with a text box directly in my project it works properly but when i bind it to the text property of textbox in usercontrol it brings null and the binding does not work.
can any one help me?

Answer

Your dependency property declaration is wrong. It has to look like shown below, where the getter and setter of the CLR property wrapper call the GetValue and SetValue methods:

public static readonly DependencyProperty TextBoxTextProperty =
    DependencyProperty.Register(
        "TextBoxText", typeof(string), typeof(TextBoxUnitConvertor));

public string TextBoxText
{
    get { return (string)GetValue(TextBoxTextProperty); }
    set { SetValue(TextBoxTextProperty, value); }
}

In the XAML of your UserControl, you would bind to the property like this:

<TextBox Text="{Binding TextBoxText,
    RelativeSource={RelativeSource AncestorType=UserControl}}" />