繁体   English   中英

用户控件数据绑定第一次不起作用

[英]User Control databinding doesn't work first time

myUserControl包含两个控件。 一个textbox和一个标签。 该用户控件在类库中。 它将在其他几个项目中使用。

我将像这样绑定。

myControl1.Databindings.Add("DataSource",myObject,"PropertyName");

在这里, PropertyName将直接与文本框绑定(我很成功),并且我已经在myObject定义了一个属性,以使用PropertyName获得标签名称。 因此,当userControl设置标签和文本框时,它需要整个绑定才能同时绑定标签和文本框数据。

我所做的是在这里(在控制中):

private object dataSource;
    [DefaultValue("")]
    public Object DataSource
    {
        get
        {
            return dataSource;
        }
        set
        {
            dataSource = value;

            OnPropertyChanged(new PropertyChangedEventArgs("DataSource"));
            BindControls();
            if (dataSource != null)
            {
                textBox1.Text = dataSource.ToString();
            }

        }
    }

    //Method to bind datasource with controls
    public void BindControls()
    {
        if (this.DataBindings.Count > 0)
        {
            //Get the instance of the binded object
            object myObj = this.DataBindings[0].DataSource as object;

            //Get binded field name as string
            string bindingField = this.DataBindings[0].BindingMemberInfo.BindingField;

            //Get Type of the binded object
            Type t1 = myObj.GetType();

            //Get property information for the binded field
            PropertyInfo property = t1.GetProperty(bindingField);

            //Get text value for label
            LabelText = property.GetAttribute<DisplayNameAttribute>(false).DisplayName;
            textBox1.ForeColor = Color.Black;
            //If textbox data is null or empty, get descrition or comment as the textbox text.
            if (string.IsNullOrEmpty(dataSource.ToString()))
            {
                dataSource = property.GetAttribute<DescriptionAttribute>(false).Description;
                textBox1.ForeColor = Color.DarkGray;
            }
        }
    }

当我从使用此控件的FORM绑定数据源时,尽管文本框包含正确的值,但标签文本为空。 我找到原因的原因是,DataBinding保持为空。

在我的表单中,我使用了一个复选框来切换对象值。 当我检查该值时,Usercontrol获得了数据绑定,随后一切正常。

问题出在您提出的财产变更中。 该字符串应与属性名称相同。 试试这样的东西...

 public string Name
        {
            get { return m_Name; }
            set
            {
                if (m_Name != value)
                {
                    m_Name = value;
                    OnChange("Name");
                }
            }
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM