问题
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;
}
}
}
回答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;}
}
回答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" };
回答3:
If your are starting to bind properties I suggest you check some articles on MVVM. This is a very powerful architecture you can use on WPF. I found it very useful in my projects. Check this one.
来源:https://stackoverflow.com/questions/5032602/binding-a-textbox-to-a-property-in-wpf