绑定到用户控件中的控件?

时间:2016-06-10 08:10:45

标签: c# winforms data-binding

我有一个简单的模型:

public class MyModel
{
    public string Property1 { get; set; }
    public string Property2 { get; set; }
}

我还有一个带有2个文本框的自定义控件。代码隐藏是:

[DefaultBindingProperty("Property1")]
public partial class MyCustomControl : UserControl
{
    public event EventHandler Property1Changed;
    public event EventHandler Property2Changed;

    [Bindable(BindableSupport.Yes, BindingDirection.TwoWay)]
    public string Property1
    {
        get { return txtProperty1.Text; }
        set 
        {
            if (txtProperty1.Text != value)
            {
                txtProperty1.Text = value;
                OnProperty1Changed(new EventArgs());
            }
        }
    }

    [Bindable(BindableSupport.Yes, BindingDirection.TwoWay)]
    public string Property2
    {
        get { return txtProperty2.Text; }
        set 
        {
            if (txtProperty2.Text != value)
            {
                txtProperty2.Text = value;
                OnProperty2Changed(new EventArgs());
            }
        }
    }

    private void OnProperty1Changed(EventArgs e)
    {
        Property1Changed?.Invoke(this, e);
    }

    private void OnProperty2Changed(EventArgs e)
    {
        Property2Changed?.Invoke(this, e);
    }

    private void txtProperty1_Validated(object sender, EventArgs e)
    {
        OnProperty1Changed(e);
    }

    private void txtProperty2_Validated(object sender, EventArgs e)
    {
        OnProperty2Changed(e);
    }
}

usercontrol放在表单上,​​数据绑定是:

myControl.DataBindings.Add(new Binding("Property1", this.bindingSource, "Property1", true, DataSourceUpdateMode.OnPropertyChanged));
myControl.DataBindings.Add(new Binding("Property2", this.bindingSource, "Property2", true, DataSourceUpdateMode.OnPropertyChanged));

但是,在更改任何usercontrol的文本框中的文本时,数据源不会更新。

我错过了什么吗?

0 个答案:

没有答案