c# - 简单的 Windows 窗体数据绑定(bind)

标签 c# winforms data-binding

假设我的表单中有一个 String 属性(并且该表单没有实现 INotifyPropertyChanged)。我还创建了一个 BindingSource 并将其 DataSource 设置为表单。然后,我将文本框绑定(bind)到表单上的 String 属性(间接地,使用 BindingSource)。

问题1:当我在运行时更改文本框中的值时,为什么我没有在String 属性的setter 中打断点?我认为将控件绑定(bind)到 String 属性将允许自动进行此方向的更新(GUI -> 成员数据)

问题 2:当 GUI 以外的其他内容更改 String 属性时,如何触发另一个方向(成员数据 -> GUI)的更新?我不想实现 INotifyPropertyChanged 接口(interface)并将 NotifyPropertyChanged 添加到 setter 。我认为通过使用 BindingSource 的 ResetBindings 我至少可以手动触发它

public partial class Form1 : Form
{
    private String m_blah;
    public String Blah
    { 
        get
        {
            return m_blah;
        }
        set
        {
            m_blah = value;
        }
    }

    public Form1()
    {
        InitializeComponent();
        textBox1.DataBindings.Add(new Binding("Text", bindingSource1, "Blah",true,DataSourceUpdateMode.OnValidation));
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Blah = "Clicked!";
        this.bindingSource1.ResetBindings(false); //expecting the GUI to update and say "Clicked!"
    }
}

最佳答案

this.bindingSource1.DataSource = this;

我想你忘了分配数据源。

关于c# - 简单的 Windows 窗体数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16074783/

相关文章:

WPF ComboBox 绑定(bind)行为

design-patterns - 数据绑定(bind)只用于 UI 吗?

c# - 具有模型导入功能的免费 opc ua 服务器

c# - 仅返回数据 GridView 的更改行?

c# - 通过箭头键限制按钮之间键盘焦点的移动

c# - 如何根据绑定(bind)对象的类型动态更改DataTemplate?

c# - PropertyGrid 中的多行字符串

c# - Linq GroupBy。返回数据子集的前一项

c# - ScrollToVerticalOffset() 不起作用?

c# - 如何获取 DataGridViewRowSelectedRowCollection 中的列