【问题标题】:CodeBehind TextBox BindingCodeBehind 文本框绑定
【发布时间】: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, 的结果为空。然而,目前还不清楚哪个 DataContext Text={Binding TopTextContent} 以前曾使用过。
  • 在不知道您的代码的情况下,我们应该如何判断?但是,如果在后面的代码中创建 Binding 之前没有设置 DataContext,那么 Binding 的 Source 显然会为 null。尽量不要设置 Source,从而使 Binding 使用以后可能设置的 DataContext。
  • 不设置Source怎么样?
  • @Clemens 我不知道这是一个选项......它确实有效。您可以将其发布为答案吗?

标签: wpf code-behind


【解决方案1】:

不要显式设置 Binding 的 Source。 Binding 将自动使用 TextBox 的 DataContext 作为源对象 - 它从其父视图元素继承其值 - 即使稍后设置:

textBox.SetBinding(
    TextBox.TextProperty, 
    new Binding
    {
        Path = new PropertyPath(propName),
        Mode = BindingMode.TwoWay
    });

【讨论】:

    【解决方案2】:

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

    我通过 DataContextChanged 事件解决了这个问题:

    public SpecificInformationView()
    {
      InitializeComponent();
    
      DataContextChanged += OnDataContext;
    }
    
    private void OnDataContext(object sender, DependencyPropertyChangedEventArgs e)
    {
      InputContextMenu("Top Text", "TopTextContent");
    }
    

    【讨论】:

      猜你喜欢
      • 2019-08-08
      • 2019-02-20
      • 2010-10-05
      • 2012-11-23
      • 1970-01-01
      • 1970-01-01
      • 2012-11-24
      • 2012-02-08
      • 2018-09-02
      相关资源
      最近更新 更多