我已经实例化了一个类“my_font_size”,它有一个访问器“Size_Points”,我试图将其绑定(bind)到多个控件。
这就是我正在尝试的:
textBox1.DataBindings.Add("Font.Size", my_font_size, "Size_Points", false, DataSourceUpdateMode.OnPropertyChanged);
但是我得到了一个 Argument.Exception,
Cannot bind to the property 'Font.Size' on the target control.
如何深入了解该属性?
最佳答案
winforms
中的
Binding
不支持嵌套路径,您必须绑定(bind) Font
属性并使用一些 Format
事件处理程序来控制绑定(bind),如下所示:
Binding bind = new Binding("Font", my_font_size, "Size_Points");
bind.Format += (s,e) => {
var b = s as Binding;
var currentFont = b.Control.Font;
e.Value = new Font(currentFont.FontFamily,
(float) e.Value, currentFont.Style);
};
textBox1.DataBindings.Add(bind);
但是我怀疑您的类 my_font_size
没有足够的条件来使 Binding
工作。以下是如何通过遵循模式来通知某些属性的更改来完成:
public class my_font_size {
float size_Points;
public float Size_Points {
get { return size_Points;}
set {
if(size_Points != value){
size_Points = value;
OnSize_PointsChanged(EventArgs.Empty);
}
}
}
public event EventHandler Size_PointsChanged;
protected virtual void OnSize_PointsChanged(EventArgs e){
var handler = Size_PointsChanged;
if(handler != null){
handler(this, e);
}
}
}
您还可以使用INotifyPropertyChanged
,但我让这部分内容供您搜索更多内容。
关于c# - 如何将文本框中的字体大小绑定(bind)到数据源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20432544/