将文本框绑定到 WPF 中的属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5032602/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Binding a Textbox to a property in WPF
提问by Eamonn McEvoy
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 -
我在用户控件中有一个文本框,我试图从我的主应用程序更新,但是当我设置 textbox.Text 属性时,它不显示新值(即使 textbos.Text 包含正确的数据)。我试图将我的文本框绑定到一个属性来解决这个问题,但我不知道如何,这是我的代码 -
MainWindow.xaml.cs
主窗口.xaml.cs
outputPanel.Text = outputText;
OutputPanel.xaml
输出面板.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
输出面板.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;
}
}
}
}
回答by Matěj Zábsky
You have to set a DataContext in some parent of the TextBox, for example:
您必须在 TextBox 的某个父级中设置 DataContext,例如:
<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;}
}
回答by Developer
I hope this example will help you.
我希望这个例子对你有帮助。
1) Create UserControl
.
1) 创建UserControl
.
2) Add to XAML <TextBlock Text="{Binding Path=DataContext.HeaderText}"></TextBlock>
2) 添加到 XAML <TextBlock Text="{Binding Path=DataContext.HeaderText}"></TextBlock>
3) In the code behind of that UserControl
add
3)在后面的代码中UserControl
添加
public partial class MyUserControl: UserControl { public string HeaderText { set; get; } // Add this line public MyUserControl() { InitializeComponent(); DataContext = this; // And add this line } }
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
4)在控制之外,假设MainWindow Load
您必须这样做
this.gdMain = new MyUserControl{ HeaderText = "YES" };
this.gdMain = new MyUserControl{ HeaderText = "YES" };