Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.