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