我在使用DataBinding到C#中的复选框时遇到问题。复选框不反映其绑定到的对象的值。
我使用了“ checkBox1.DataBindings.Add(” Checked“,cb,” t“,false,DataSourceUpdateMode.OnPropertyChanged)”将简单的数据源绑定到对象cb。对象中的bool属性“ t”会根据复选框的选中状态进行更新,但是复选框的选中状态不反映对象的状态(cb.t)。
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
test cb = new test();
public Form1()
{
InitializeComponent();
cb.t = false;
checkBox1.DataBindings.Add("Checked", cb, "t", false, DataSourceUpdateMode.OnPropertyChanged);
}
private void button1_Click(object sender, EventArgs e)
{
cb.t = true;
//checkBox1.Refresh();
//checkBox1.Invalidate();
}
}
public class test
{
public bool t { set; get; }
}
}
如果我单击button1,则复选框的状态不会更改;但是,如果我在窗体加载时在构造函数中设置cb.t = true,则复选框选中状态与cb.t的值相同。谢谢你的帮助。
答案 0 :(得分:0)
属性更改时,不会通知您的视图更新。见- How To: INotifyPropertyChanged
尝试进行这些更改-
using System.ComponentModel;
using System.Runtime.CompilerServices;
public class test : INotifyPropertyChanged
{
private bool _t;
public bool t {
get { return _t; }
set
{
if (value != _t)
{
_t = value;
NotifyPropertyChanged();
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
// This method is called by the Set accessor of each property.
// The CallerMemberName attribute that is applied to the optional propertyName
// parameter causes the property name of the caller to be substituted as an argument.
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}