Eam*_*voy 4 data-binding wpf user-controls dependency-properties properties
我在用户控件中有一个文本框我试图从我的主应用程序更新但是当我设置textbox.Text属性时它不显示新值(即使textbos.Text包含正确的数据).我试图将我的文本框绑定到属性以解决这个问题,但我不知道如何,这是我的代码 -
MainWindow.xaml.cs
outputPanel.Text = outputText;
Run Code Online (Sandbox Code Playgroud)
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 -->
Run Code Online (Sandbox Code Playgroud)
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;
}
}
Run Code Online (Sandbox Code Playgroud)
}
您必须在TextBox的某个父级中设置DataContext,例如:
<UserControl Name="panel" DataContext="{Binding ElementName=panel}">...
Run Code Online (Sandbox Code Playgroud)
然后绑定将是:
Text="{Binding Text}"
Run Code Online (Sandbox Code Playgroud)
你不应该需要这个 - 从代码背后的具体元素来看通常是不好的做法:
public TextBox Textbox
{
get {return textbox;}
}
Run Code Online (Sandbox Code Playgroud)
我希望这个例子对你有帮助。
1) 创建UserControl.
2) 添加到 XAML <TextBlock Text="{Binding Path=DataContext.HeaderText}"></TextBlock>
3)在后面的代码中UserControl添加
Run Code Online (Sandbox Code Playgroud)public partial class MyUserControl: UserControl { public string HeaderText { set; get; } // Add this line public MyUserControl() { InitializeComponent(); DataContext = this; // And add this line } }
4)在控制之外,假设MainWindow Load您必须这样做
this.gdMain = new MyUserControl{ HeaderText = "YES" };
| 归档时间: |
|
| 查看次数: |
31896 次 |
| 最近记录: |