问题
I am binding many controls on my form to an object returned from a method call like so:
textBoxMoonBeam.DataBindings.Add(new Binding("Text", pi, "MoonBeam"));
Note: "pi" is the name of an instantiation of the PlatypusInfo class.
...but when I am grabbing a dateTime value, which by definition includes the time appended to the date, but I only want to show the date in the control, I've got to eschew the type of binding above and instead do this:
textBoxDateAztecsFirstSawElvis.Text = pi.DateAztecsFirstSawElvis.ToString("d");
Is there a way to bind my data like the first example, and still truncate the date?
回答1:
Use the binding source's Format event.
Something like this:
Binding binding = new Binding("Text", pi, "DateAztecsFirstSawElvis", true);
binding.Format += binding_Format;
textBoxDateAztecsFirstSawElvis.DataBindings.Add(binding);
void binding_Format(object sender, ConvertEventArgs e) {
e.Value = ((DateTime)e.Value).ToShortDateString();
}
来源:https://stackoverflow.com/questions/10639477/is-there-a-non-klunky-way-to-perform-special-case-formatting-with-bound-data