Skip to content

Instantly share code, notes, and snippets.

@upsilon
Created April 26, 2014 14:49
Show Gist options
  • Save upsilon/11322044 to your computer and use it in GitHub Desktop.
Save upsilon/11322044 to your computer and use it in GitHub Desktop.
WinForms のデータバインディングに関する妄想
this.LabelScreenName.DataBindings.Add("Text", this.bindingSource, "ScreenName");
var binding = new Binding("Text", this.bindingSource, "Name");
binding.Format += (o, e) => e.Value = WebUtility.HtmlDecode(e.Value);
this.LabelName.DataBindings.Add(binding);
// ↑これを
// ↓ こんな感じに書きたい
BindToText(this.LabelScreenName, this.bindingSource,
(User x) => x.ScreenName, null);
BindToText(this.LabelName, this.bindingSource,
(User x) => x.Name, x => WebUtility.HtmlDecode(x));
private static void BindToText<T1, T2>(Control control, object source,
Expression<Func<T1, T2>> expr, Func<T2, object> formatter)
{
var memberExpr = (MemberExpression)expr.Body;
var binding = new Binding("Text", source, memberExpr.Member.Name);
if (formatter != null)
binding.Format += (o, e) => e.Value = formatter((T2)e.Value);
control.DataBindings.Add(binding);
}
@upsilon
Copy link
Author

upsilon commented Apr 26, 2014

さらにこんな感じで書けると尚よい

BindToText(this.LabelName, this.bindingSource, (User x) => WebUtility.HtmlDecode(x.Name));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment