将文本框绑定到WPF中的属性

问题描述:

我在用户控件中有一个文本框我试图从我的主应用程序更新,但是当我设置textbox.Text属性它不会显示新的值(即使textbos.Text包含正确的数据)。我试图将我的文本框绑定到一个属性来解决这个问题,但我不知道如何,这里是我的代码 -

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

}

}

您必须在TextBox的某个父项中设置DataContext,例如:

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

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

然后绑定将是:

Text="{Binding Text}"

你不应该这样 - 指代码背后的特定元素通常是不好的做法: p>

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

public TextBox Textbox
{
    get {return textbox;}
}