CodeBehind文本框绑定

问题描述 投票:0回答:2

我的目标是在后面的代码中用它替换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它应该可以工作,但是不能,该字段确实出现,但是输入字段为空,并且对其进行修改不会修改应该绑定到的值。

窥探显示为红色:

showcasing that snoop does show {Path=TopTextContent} but in red

我不确定如何进一步调试它或我做错了。

wpf code-behind
2个回答
0
投票

我还没有完全了解这一切,但似乎我的DataContext确实在构造函数之后被填充(因此它仍然为null)。

我通过DataContextChanged事件解决了它:

public SpecificInformationView()
{
  InitializeComponent();

  DataContextChanged += OnDataContext;
}

private void OnDataContext(object sender, DependencyPropertyChangedEventArgs e)
{
  InputContextMenu("Top Text", "TopTextContent");
}

0
投票

不要显式设置绑定的源。它将自动使用TextBox的DataContext-即使稍后设置,它也会从其父视图元素继承其值:

textBox.SetBinding(
    TextBox.TextProperty, 
    new Binding
    {
        Path = new PropertyPath(propName),
        Mode = BindingMode.TwoWay
    });
© www.soinside.com 2019 - 2024. All rights reserved.