【发布时间】:2020-04-20 18:28:43
【问题描述】:
我的目标是将 xaml 视图中的 <TextBox Text={Binding TopTextContent} />(按原样工作)替换为后面代码中的这个:
public partial class MyView: UserControl
{
public MyView()
{
InitializeComponent();
// Supposed to replace: // <TextBox Text={Binding TopTextContent} />
InputContextMenu("Top Text", "TopTextContent");
}
private void InputContextMenu([NotNull] string header, [NotNull] string propName)
{
var textBox = new TextBox
{
MaxLength = 12,
Width = 80,
FocusVisualStyle = null
};
textBox.SetBinding(
TextBox.TextProperty,
new Binding
{
Path = new PropertyPath(propName),
Source = DataContext, // (MyView)DataContext didn't work as well
Mode = BindingMode.TwoWay
}
);
CodeBehindTextInputs.Items.Add(
new MenuItem
{
Header = header,
Focusable = false,
Items = {textBox}
}
);
}
}
Afaik 它应该可以工作但它没有,该字段确实出现但输入字段为空并且修改它不会修改它应该绑定到的值。
Snoop 显示为红色:
我不确定如何进一步调试它或我做错了什么。
【问题讨论】:
-
d:something用于设计时,在运行时不起作用 -
d:DataContext仅设置设计时 DataContext,因此Source = DataContext,的结果为空。然而,目前还不清楚哪个 DataContextText={Binding TopTextContent}以前曾使用过。 -
在不知道您的代码的情况下,我们应该如何判断?但是,如果在后面的代码中创建 Binding 之前没有设置 DataContext,那么 Binding 的 Source 显然会为 null。尽量不要设置 Source,从而使 Binding 使用以后可能设置的 DataContext。
-
不设置Source怎么样?
-
@Clemens 我不知道这是一个选项......它确实有效。您可以将其发布为答案吗?
标签: wpf code-behind