Binding a Textbox to a property in WPF

38,341

Solution 1

You have to set a DataContext in some parent of the TextBox, for example:

<UserControl Name="panel" DataContext="{Binding ElementName=panel}">...

Then the binding will be:

Text="{Binding Text}"

And you shouldn't need this - referring to specific elements from code behind is usually bad practice:

public TextBox Textbox
{
    get {return textbox;}
}

Solution 2

I hope this example will help you.

1) Create UserControl.

2) Add to XAML <TextBlock Text="{Binding Path=DataContext.HeaderText}"></TextBlock>

3) In the code behind of that UserControl add

public partial class MyUserControl: UserControl

    {
        public string HeaderText { set; get; } // Add this line

        public MyUserControl()
        {
            InitializeComponent();

            DataContext = this; // And add this line
        }
    }

4) Outside of the control and let's say in the MainWindow Load event you have to do like

this.gdMain = new MyUserControl{ HeaderText = "YES" };

Share:
38,341
Eamonn McEvoy
Author by

Eamonn McEvoy

Updated on April 19, 2020

Comments

  • Eamonn McEvoy
    Eamonn McEvoy about 4 years

    I have a Textbox in a User Control i'm trying to update from my main application but when I set the textbox.Text property it doesnt display the new value (even though textbos.Text contains the correct data). I am trying to bind my text box to a property to get around this but I dont know how, here is my code -

    MainWindow.xaml.cs

    outputPanel.Text = outputText;
    

    OutputPanel.xaml

    <TextBox x:Name="textbox" 
                 AcceptsReturn="True" 
                 ScrollViewer.VerticalScrollBarVisibility="Visible"
                 Text="{Binding <!--?????--> }"/>  <!-- I want to bind this to the Text Propert in OutputPanel.xmal.cs -->                               
    

    OutputPanel.xaml.cs

     namespace Controls
    {
    public partial class OutputPanel : UserControl
    {
        private string text;
    
        public TextBox Textbox
        {
            get {return textbox;}
        }
    
        public string Text
        {
            get { return text; }
            set { text = value; }
        }
    
        public OutputPanel()
        {
            InitializeComponent();
            Text = "test";
            textbox.Text = Text;
        }
    
    }
    

    }