【问题标题】:Binding String property to TextBox Text from Code Behind从后面的代码将字符串属性绑定到文本框文本
【发布时间】:2019-08-07 13:06:03
【问题描述】:

抱歉这个基本问题

我有一个数据模型:

class data_test
    {
        public string textdata { get; set; }
        public bool booldata { get; set; }
        public bool checkdata { get; set; }
        public data_opt enumdata { get; set; }
    }

这里是枚举:

   enum data_opt
        {
            managed = 1,
            unmanaged = 2 ,
            mixed = 3
        }

然后我创建一个数据模型:

    var n_Data = new data_test()
    { textdata = "test data",
    booldata = false,
    checkdata = true ,
    enumdata = data_opt.mixed
    };

我从后面的代码创建了一个文本框:

 var text_box = new TextBox();

现在我想将 text_box.Text 属性从后面的代码绑定到 n_Data.textdata

DataGrid工作方式相同,双向连接,实时更新。

我找到了一些页面:

Binding String Property in Code-Behind TextBlock

WPF Data Binding to a string property

Binding string property to object

不幸的是,它们都不适合我,这是我要绑定的代码:

Binding binding = new Binding();
binding.Path = new PropertyPath("textdata");
binding.Source = n_Data;
text_box.SetBinding(TextBlock.TextProperty, binding);

我也试过这个:

    Binding binding = new Binding();
    binding.Path = new PropertyPath("textdata");
    binding.Source = n_Data;
    BindingOperations.SetBinding(text_box, TextBlock.TextProperty, binding);

两个都不行,我做错了什么?

【问题讨论】:

  • 您尚未将 datacontext 设置为您的视图模型。您还没有实现 inotifyprooertychanged,即使您不想更改 vm 中的数据并看到视图响应,也应该这样做。
  • 显式设置Binding的Source时不需要设置DataContext。当然,您只需在您的逻辑实际需要属性更改通知时实现 INotifyPropertyChanged。
  • @Andy 据我所知,没有必要使用 INotifyPropertyChanged 和 DataContext 进行单一绑定...我按照 Fruchtzwerg 所说的做了,现在工作正常...
  • @Clemens ,它工作正常,我真的需要INotifyPropertyChanged 吗?我更改值和 GUI 更改,我更改 GUI 和值更改,为什么我需要 INotifyPropertyChanged?
  • 如前所述,不需要的时候当然不需要实现。

标签: c# wpf


【解决方案1】:

由于您的目标是TextBox,因此您不能使用TextBlock.TextProperty 作为属性进行绑定。你需要使用TextBox.TextProperty:

text_box.SetBinding(TextBox.TextProperty, binding);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-25
    • 2017-01-01
    • 1970-01-01
    相关资源
    最近更新 更多