Saturday, April 11, 2009

Data bindings


Data bindings in C# are something I've totally ignored because I've always assumed they're boring database related code.

Yesterday I ported my simple particle system from C++ to C#. Previously I'd defined particle systems in my own special file format and then used that to create them. So I'd edit the file then load the test program and see what it looked like. (I may even have had a quick reload key, that reset the particle system with the new data)

In C# I thought I may as well have a second window with a load of controls on it. This is about two lines of code in C# and some mouse clicking. I remembered when I was doing some MFC stuff I could have a text box that had a pointer to a value of an object. So the data was totally real time, the number in the box was the number in the object.

I wondered if databindings would let me do something similar in C# and cut down on the amount of code I'd need to write. Here's what I've got at the moment:


public partial class ParticleTester : Form
{
ParticleSystem _system;
public ParticleTester(ParticleSystem system)
{
_system = system;
InitializeComponent();

particleSizeBox.DataBindings.Add("Text", _system, "ParticleSize");
}
}


That's the entire class. What the data binding means is - get the 'Text' field from the textbox 'particleSizeBox' and fill it up with data from _system.ParticleSize. This works both ways - if I change that value in the text box the value in my particle system changes. Very neat and quick - it's handles changing from a number to string and back again automagically.

Obviously I'm a little late to the party on databindings but it's nice to find something new and useful.



Just in case you want to know - this is how I did a combo box:


comboType.DataSource = System.Enum.GetValues(typeof(ParticleSystem.eParticleType));
comboType.DataBindings.Add("SelectedItem", _system, "ParticleType");
Post a Comment