Reputation: 7591
Is there any way to get custom binding behavior in .net win forms?
Example, I'm connecting my control to a BindingSource object and adding a binding like
this.slider.DataBindings.Add(new System.Windows.Forms.Binding("Enabled", this.bindingSourceModel, "FloatProperty > 0.5f", true));
There's no way the above will work but I like it to be enabled if dataSource.FloatProperty becomes greater than 0.5f.
Is there any way to do this?
Upvotes: 2
Views: 709
Reputation: 4855
I understand what you want to do, so I've slightly modified your situation for the sake of demonstration: the UI setup is obvious, there is a TrackBar
and a Button
, and the problem here is to bind the Enabled
property of button
to the boolean value of the expression trackBar.Value > 50
.
The idea is to turn the main form into something like a ViewModel (as in MVVM). Observe that I am implementing 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;
...
}
Now, this is my personal observation: While there is a non-trivial interpretation of your goal, your goal is a bit maniacal. You have to ponder why exactly you want to achieve this through data-binding. Binding is mostly aimed for automatic, bi-directional, sync'ing of property values. Doing this type of UI update via binding directly to the "model" is even more maniacal. But you got credit for being maniacal, though! ;-)
Upvotes: 1