我的目标是在后面的代码中用它替换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它应该可以工作,但是不能,该字段确实出现,但是输入字段为空,并且对其进行修改不会修改应该绑定到的值。
窥探显示为红色:
我不确定如何进一步调试它或我做错了。
我还没有完全了解这一切,但似乎我的DataContext确实在构造函数之后被填充(因此它仍然为null)。
我通过DataContextChanged
事件解决了它:
public SpecificInformationView()
{
InitializeComponent();
DataContextChanged += OnDataContext;
}
private void OnDataContext(object sender, DependencyPropertyChangedEventArgs e)
{
InputContextMenu("Top Text", "TopTextContent");
}
不要显式设置绑定的源。它将自动使用TextBox的DataContext-即使稍后设置,它也会从其父视图元素继承其值:
textBox.SetBinding(
TextBox.TextProperty,
new Binding
{
Path = new PropertyPath(propName),
Mode = BindingMode.TwoWay
});