lundi 25 septembre 2017

WPF: Mechanism or design pattern for property meta data

I'm starting a big WPF project and I'm thinking about how to manage a specific aspect of it, which is data validation.

The way I see it, any property in a Model should have some basic properties of its own, such as MaxLength, MinLength, IsRequired, AcceptsNulls, etc. These properties will often be bound to some aspects of a XAML file, such as custom ControlTemplate for controls bound to properties where IsRequired = true, setting MaxLength automatically on TextBoxes, etc.

I could create a class similar to this one:

public class PropertyMetaData<T> {
    public int MaxLength { get; set }
    public bool IsRequired { get; set; }
}

and then my model will have something like:

public MyClass {
    public PropertyMetaData<string> Name { get; set; }
}

Now I can bind a XAML element like this:

<TextBox Text="{Binding Name}" MaxLength="{Binding Name.MaxLength}" DataTemplateSelector="{Binding Name.IsRequired, ValueConverter={...}}"/>

  • etc.

This makes general sense to me, but when you get down to implementation, there are a few little caveats that I need to resolve.

Now, I simply don't want to re-invent the wheel. So I looked it up on Google and couldn't find out: Is there some built-in mechanism for this in WPF? Perhaps a design pattern?

Any help will be appreciated!

Aucun commentaire:

Enregistrer un commentaire