Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding a Textbox to a property in WPF

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;
    }

}

}

like image 433
Eamonn McEvoy Avatar asked Feb 17 '11 17:02

Eamonn McEvoy


People also ask

What is databinding in WPF?

Data binding in Windows Presentation Foundation (WPF) provides a simple and consistent way for apps to present and interact with data. Elements can be bound to data from different kinds of data sources in the form of . NET objects and XML.

What is binding source in WPF?

A binding source is usually a property on an object so you need to provide both the data source object and the data source property in your binding XAML. In the above example the ElementName attribute signifies that you want data from another element on the page and the Path signifies the appropriate property.

What is DataContext in WPF?

The DataContext property is the default source of your bindings, unless you specifically declare another source, like we did in the previous chapter with the ElementName property. It's defined on the FrameworkElement class, which most UI controls, including the WPF Window, inherits from.


1 Answers

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;}
}
like image 99
Matěj Zábský Avatar answered Sep 29 '22 05:09

Matěj Zábský