【问题标题】:custom binding .net forms自定义绑定 .net 表单
【发布时间】:2012-06-29 14:48:24
【问题描述】:

有没有办法在 .net win 表单中获得自定义绑定行为?

例如,我将控件连接到 BindingSource 对象并添加类似的绑定

this.slider.DataBindings.Add(new System.Windows.Forms.Binding("Enabled", this.bindingSourceModel, "FloatProperty  > 0.5f", true));

上述方法无法正常工作,但我希望在 dataSource.FloatProperty 大于 0.5f 时启用它。

有什么办法吗?

【问题讨论】:

    标签: c# winforms binding


    【解决方案1】:

    我明白你想要做什么,所以为了演示,我稍微修改了你的情况:UI设置很明显,有一个TrackBar和一个Button,这里的问题是绑定将buttonEnabled 属性转换为表达式trackBar.Value > 50 的布尔值。

    这个想法是将主要形式变成类似于 ViewModel 的东西(如在 MVVM 中)。观察我正在实施INotifyPropertyChanged

    public partial class ManiacalBindingForm : Form, INotifyPropertyChanged {
    
        public ManiacalBindingForm() {
            InitializeComponent();
    
            this.button.DataBindings.Add("Enabled", this, "ManiacalThreshold", true, DataSourceUpdateMode.OnPropertyChanged);
    
            this.trackBar.ValueChanged += (s, e) => {
                this.Text = string.Format("ManiacalBindingForm: {0}", this.trackBar.Value);
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs("ManiacalThreshold"));
            };
        }
    
        public bool ManiacalThreshold {
            get { return this.trackBar.Value > 50; }
        }
    
        public event PropertyChangedEventHandler PropertyChanged;
    
        ...
    }
    

    现在,这是我个人的观察:虽然对你的目标有不平凡的解释,但你的目标有点疯狂。您必须思考为什么要通过数据绑定来实现这一目标。绑定主要针对属性值的自动、双向同步。通过直接绑定到“模型”来进行这种类型的 UI 更新更加疯狂。但是,您因疯狂而受到赞誉! ;-)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-06
      • 2020-11-03
      • 2020-05-29
      • 2018-06-08
      • 1970-01-01
      • 2022-01-01
      相关资源
      最近更新 更多