Skip to content

Instantly share code, notes, and snippets.

@lordofscripts
Created September 14, 2017 18:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lordofscripts/29c04c332411be8a60560724f1581c05 to your computer and use it in GitHub Desktop.
Save lordofscripts/29c04c332411be8a60560724f1581c05 to your computer and use it in GitHub Desktop.
Using Data Annotations to configure WinForm controls as per the constraint set in the model
using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace LordOfScripts.Gists.Windows.Forms.Models
{
// This is your entity model, not necessarily for Entity Framework
public class AnyPersonModel
{
[Key]
public int AnyPersonId { get; set; }
[Required, StringLength(40)]
public string FirstName { get; set; }
[Required, StringLength(50)]
public string LastName { get; set; }
}
}
using System;
using System.Windows.Forms;
using LordOfScripts.Gists.Extensions;
namespace LordOfScripts.Gists.Windows.Forms.Views
{
// This would be any windows forms in which you want to configure your controls to match the
// constraints you set in your (entity) model
public partial class AnyView : Form
{
public AnyView(AnyPersonModel model)
{
InitializeComponent();
ConfigureConstraints(model);
}
private void ConfigureConstraints(AnyPersonModel model)
{
// Make sure we set the MaxLength of our textboxes to match the entity model constraints
textBoxFirstName.MaxLength = model.GetAttributeFrom<StringLengthAttribute>("FirstName").MaximumLength;
textBoxLastName.MaxLength = model.GetAttributeFrom<StringLengthAttribute>("LastName").MaximumLength;
}
}
}
using System;
using System.Windows.Forms;
namespace LordOfScripts.Gists.Extensions
{
public static class DataAnnotationExtensions
{
/// <summary>
/// (extension) Retrieve the <see cref="System.ComponentModel.DataAnnotations"/> attribute from a
/// class property.
/// </summary>
/// <typeparam name="T">The attribute type, i.e. StringLengthAttribute, MaxLengthAttribute</typeparam>
/// <param name="instance">the class instance where the property will be inspected</param>
/// <param name="propertyName">The class property to which the attribute has been applied</param>
/// <returns>The attribute value</returns>
/// <example>
/// var name = player.GetAttributeFrom<DisplayAttribute>("PlayerDescription").Name;
/// var maxLength = player.GetAttributeFrom<MaxLengthAttribute>("PlayerName").Length;
/// </example>
public static T GetAttributeFrom<T>(this object instance, string propertyName) where T : Attribute
{
var attrType = typeof(T);
var property = instance.GetType().GetProperty(propertyName);
return (T)property.GetCustomAttributes(attrType, false).First();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment